title: react onClick always only select last element
body: <p>I was trying to do a onClick function inside navbar component but i noticed everytime the onclick function only works on the last element of the list. It does not matter which element i click on it always affects the last element only. Here's my Navbar component and listItem component -</p>
  <p>Navbar:</p>
  <pre><code>import './Navbar.scss';
  import ListItem from '../ListItem/ListItem';
  import { navLinks } from '../../staticData';
  import { useRef } from 'react';
  
  const Navbar = () =&gt; {
      const itemRef = useRef();
      const handleClick = () =&gt; {
          itemRef.current.style.background = 'red'
      };
  
    return (
      &lt;div className='navbar'&gt;
          &lt;ul className=&quot;navbarList&quot;&gt;
              {
                  navLinks.map((item, index) =&gt; (
                      &lt;ListItem item={item} key={index} onClick={handleClick} itemRef={itemRef}/&gt;
                  ))
              }
          &lt;/ul&gt;
      &lt;/div&gt;
    )
  }
  
  export default Navbar
  </code></pre>
  <p>listItem Component:</p>
  <pre><code>import './ListItem.scss';
  import { Link } from 'react-router-dom';
  
  const ListItem = ({ item, onClick, itemRef }) =&gt; {
    return (
      &lt;Link onClick={onClick} ref={itemRef} className='listItemWrapper' to=''&gt;
        &lt;li className=&quot;listItem&quot;&gt;{item.name}&lt;/li&gt;
      &lt;/Link&gt;
    )
  }
  
  export default ListItem
  </code></pre>
  <p>Example - <a href="https://i.stack.imgur.com/8GJSd.png" rel="nofollow noreferrer">Example Image</a></p>