Uhney
Uhney

Reputation: 473

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.

Upvotes: 0

Views: 1590

Answers (2)

Uhney
Uhney

Reputation: 473

According to what @MuhammedJaseem said, I updated my code below, and it works well.

const repeatCode = (list, onChange) => { // Added
  return (
    <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))}
        onChange={e => onChange(e.target.checked, list.slug, dynamicType)} // Added
      />
    </div>
)}
<div >
{ selected ? (
  dynamicData
    .sort((a, b) => b.count_filtered - a.count_filtered) 
    .map((list, idx) => (
      repeatCode(list, handleSelect)
    ))
) : (
  dynamicData.map((list, idx) => (
      repeatCode(list, handleSelect)
  ))
)}
</div>

Upvotes: 1

Muhammed Jaseem
Muhammed Jaseem

Reputation: 840

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>

Upvotes: 0

Related Questions