setState inside map function

Help Wanted

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

https://preview.redd.it/pnpwykhbk8a71.png?width=200&format=png&auto=webp&s=9e95c27610d3be3b0cd5b3999768ccd14e6827c2

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
Loading comments…