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

Time:02-16

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.

CodePudding user response:

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>
  • Related