ReactJs – how to keep only one "active" section at a time


I’m having issues with finding a solution or correct direction for my problem. At the moment once you click on -> className="List-section", it will show the information in -> className="Paragraph-container", but there are 4 sections of it and I want to only allow one section to be open at a time. At the moment I can open all of them and be displayed.
If it helps, here’s the link to the prototype(and how the flow should be): https://www.figma.com/proto/ooya7hVTx4BvdwQQFPXZcj/CCT-Lab-task?node-id=5%3A711&scaling=min-zoom&page-id=0%3A1&starting-point-node-id=5%3A509

Thanks for all the help in advance!

Parent Component

function App() {
  const data = [
    {
      title: "Build test task",
      items: [
        "Create repositor",
        "Implement designs",
        "Implement functionality",
      ],
    },
    {
      title: "Submit your test task",
      items: [
        "Open email client",
        "Sent link information to [email protected]",
      ],
    },
    {
      title: "Participate in tech interview",
      items: ["Talk with HR", "Talk with Tech team"],
    },
    {
      title: "Reciece anster",
      items: ["Receive answers", "Start your IT career"],
    },
  ];

  return (
    <div className="App">
      <header className="App-header">
        <h1>CCT Lab Process</h1>
      </header>
      <div className="App-content">
      {data.map((dataObject, index) => (
        <ListItem key={index} listData={dataObject} listNumber={index + 1} />
      ))}
      </div>

    </div>
  );
}

Child Component

function ListItem({ listNumber, listData }) {
  const [isShownOne, setIsShownOne] = useState(false);

  return (
    <div className="List">
      <div className="List-section" onClick={() => setIsShownOne(!isShownOne)}
      >
        <div className="Section-item">{listNumber}</div>
        <p className="Section-title">{listData.title}</p>
      </div>
      {isShownOne && (
        <div className="List-paragraph">
          {listData.items.map((paragraphItem, index) => (
            <div className="Paragraph-container" key={index}>
              <CheckedIcon  />
              <p className="Paragraph-item">{paragraphItem}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

BTW, tried to google all possible options but was not able to find a solution. Some suggest checking id in the Parent component and passing the logic to the Child. Feeling a bit lost at the moment!

Source: React – Stack Overflow

November 5, 2021
Category : News
Tags: components | javascript | onclick | react hooks | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.