Search code examples
htmlreactjsjsxtoggledisplay

How to toggle/display content individually in ReactJS


my question is how can I toggle/display the "Some text" content on onClick individually?. I can use different function and state for every div an it is working but I know this is not the correct way to do it . Can you help me with this guys? Thanks

This is my code

function App() {
  const [loaded, setLoaded] = useState(true);
  const [show, setShow] = useState(false);

  const handleShow = () => {
    setShow(!show);
  };

  return (
    <div className={styles.App}>
      {loaded && (
        <div className={styles.cards_container}>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
          <div className={styles.card_container} onClick={handleShow}>
            <h3>Title</h3>
            {show && (
              <div>
                <p>Some text</p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Solution

  • You could create a custom component for your card that handles the state for each card:

    function Card() {
        const [show, setShow] = useState(false);
    
        const handleShow = () => {
          setShow(state => !state);
        };
    
        return <div className={styles.card_container} onClick={handleShow}>
          <h3>Title</h3>
    
          {show && (
              <div>
                <p>Some text</p>
              </div>
          )}
        </div>
    }
    

    And use it in your app:

    function App() {
      const [loaded, setLoaded] = useState(true);
    
      return (
        <div className={styles.App}>
          {loaded && (
            <div className={styles.cards_container}>
              <Card />
              <Card />
              <Card />
            </div>
          )}
        </div>
      );
    }