setState inside map function
I have a list in my app like so, I am rendering this list using map function. I can also hard code each element inside a <Li> tag
I want each list item to call setState on mouse click, the state that will be set will depend on the value of list item, i.e
<li> All </li> will set State to 'All', <li> JS </li> will get State to 'JS'and so on
const array = [
{
category: 'All'
classNames: '...'
},
{
category: 'JS'
className: '...'
},
{
category: 'CSS'
classNames: '...'
},
...
{
category: 'Java'
classNames: '...'
}
];
const [state, setState] = useState('');
return (
<ul>
{array.map(items => (
<li onClick={() => setState(items.category)}>
{items.category}
</li>
))}
</ul>
);
My code obviously doesn't work. How do I do this? Should I just hardcode it or is there a better way to achieve this?
Posted Jul 9, 2021, 7:43 PM UTC · edited
013