'Toggling Issue React JS

When I press h2, all others are also showing the text which supposed to be hidden

const [show, setShow] = useState(false);
<div>
          <h2 key={1} onClick={() => setShow(!show)}>
            What is Netflix ?
          </h2>
          {show ? (
            <p>
              Netflix is a streaming service that offers a wide variety of
              award-winning TV shows, movies, anime, documentaries, and more on
              thousands of internet-connected devices. You can watch as much as
              you want, whenever you want without a single commercial – all for
              one low monthly price. There's always something new to discover
              and new TV shows and movies are added every week!
            </p>
          ) : null}
        </div>
        <div>
          <h2 onClick={() => setShow(!show)}>How much does Netflix cost?</h2>
          {show ? (
            <p>
              Watch Netflix on your smartphone, tablet, Smart TV, laptop, or
              streaming device, all for one fixed monthly fee. Plans range from
              KRW9,500 to KRW17,000 a month. No extra costs, no contracts.
            </p>
          ) : null}
        </div>

Since I am a junior, No idea what to do ))) Please help



Solution 1:[1]

You could simply use a state to identify which paragraph to show and identify each of them by any kind of identifier. Here i just use a simple number, but if you are in a loop you'll have an index. Here is a repro on Stackblitz and here is the code to achieve that :

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  const [visibleItem, setVisibleItem] = React.useState(1);
  return (
    <>
    <h2 onClick={() => setVisibleItem(1)}>Paragraph 1</h2>
    <div className={`${visibleItem === 1 ? '' : 'hidden'}`}>
      Content of the Paragraph 1
    </div>
    <h2 onClick={() => setVisibleItem(2)}>Paragraph 2</h2>
    <div className={`${visibleItem === 2 ? '' : 'hidden'}`}>
      Content of the Paragraph 2
    </div>
    <h2 onClick={() => setVisibleItem(3)}>Paragraph 3</h2>
    <div className={`${visibleItem === 3 ? '' : 'hidden'}`}>
      Content of the Paragraph 3
    </div>
    </>
  );
};

render(<App />, document.getElementById("root"));

And the css class to hide the elements :

.hidden {
  display: none;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1