'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.
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Uheny |
