title: How to toggle only one element of a collection of elements on click in ReactJS?
body: <p>I want to toggle only the last span element that says &quot;text to toggle for {user.id}&quot;, I only want to toggle this element for that specific li element, not all the li elements. Currently how I have set up, it will toggle that span element for all the li elements due to how state works. I was thinking of passing an index via the map function and referencing the index to toggle the element I want, but how can I do that? Because the state is set for all the li elements, is there a better way to do this rather than using state?</p>
  <p>I know with vanilla JS I could just use getElementById and set the style of it to hide or block. But with react I wasn't sure the best way to handle this, because I was taught we want to avoid IDs when we can with react. Then as far as using useRef() goes I wasn't sure that would really work here because I would need to create a refs for each element and I don't know that I can do that dynamically or if that would be the best practice for that matter?</p>
  <p>Thank you!</p>
  <pre><code>import React, { useState } from 'react';
  
  const Users = [
    { id: 1, name: 'Andy', age: 32 },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Tom Hulk', age: 40 },
    { id: 4, name: 'Tom Hank', age: 50 },
    { id: 5, name: 'Audra', age: 30 },
    { id: 6, name: 'Anna', age: 68 },
    { id: 7, name: 'Tom', age: 34 },
    { id: 8, name: 'Tom Riddle', age: 28 },
    { id: 9, name: 'Bolo', age: 23 },
  ];
  
  function Test() {
  
    const [toggle, setToggle] = useState('none');
  
    function toggleFunction () {
        toggle === 'none' ? setToggle('block') : setToggle('none')
    }
  
    return (
      &lt;div className=&quot;container&quot;&gt;
  
        &lt;div className=&quot;user-list&quot;&gt;
          {
            Users.map((user) =&gt; (
              &lt;li key={user.id} className=&quot;user&quot;&gt;          
                &lt;button onClick={toggleFunction}&gt;Button&lt;/button&gt;
                &lt;span className=&quot;user-id&quot;&gt;{user.id}&lt;/span&gt;
                &lt;span className=&quot;user-name&quot;&gt;{user.name}&lt;/span&gt;
                &lt;span className=&quot;user-age&quot;&gt;{user.age} year old&lt;/span&gt;
                &lt;span style={{display: toggle}}&gt;text to toggle for {user.id}&lt;/span&gt;
              &lt;/li&gt;
            ))
           }
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
  
  export default Test;
  </code></pre>