Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js: how to sort() and map() or only map() conditionally in JSX

I have this code below which doesn’t seem to be effective as I use almost the same code twice. I would like to make this code much cleaner than this by not just pasting and copying.

<div >
{ selected ? (
  dynamicData
    .sort((a, b) => b.count_filtered - a.count_filtered) // Only this part is different
    .map((list, idx) => (
      <div key={list.slug}>
        <label htmlFor={list.slug}>
          {list.name} (<b> {list.count_filtered} </b> / {list.count_all})
        </label>
        <input
          type="checkbox"
          value={list.slug}
          id={list.slug}
          checked={filterList.some(el => el.slug.includes(list.slug))}
        />
      </div>
    ))
) : (
  dynamicData.map((list, idx) => (
    <div key={list.slug}>
      <label htmlFor={list.slug}>
        {list.name} (<b> {list.count_filtered} </b> / {list.count_all})
      </label>
      <input
        type="checkbox"
        value={list.slug}
        id={list.slug}
        checked={filterList.some(el => el.slug.includes(list.slug))}
      />
    </div>
  ))
)}
</div>

As you can see, if selected is true, the array is going to sort() and map() otherwise, it will only do map().

Please let me know the clever way to clean this code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

const repeatCode = (
    <div key={list.slug}>
      <label htmlFor={list.slug}>
        {list.name} (<b> {list.count_filtered} </b> / {list.count_all})
      </label>
      <input
        type="checkbox"
        value={list.slug}
        id={list.slug}
        checked={filterList.some(el => el.slug.includes(list.slug))}
      />
    </div>
)
<div >
{ selected ? (
  dynamicData
    .sort((a, b) => b.count_filtered - a.count_filtered) // Only this part is different
    .map((list, idx) => (
      {repeatCode}
    ))
) : (
  dynamicData.map((list, idx) => (
      {repeatCode}
  ))
)}
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading