Q:

How to toggle a content of the single element in React JS?

I'm trying to implement toggle function in React JS, so when a user clicks on the title its content/text should be visible. I was able to create toggle function, but when I click on the title all texts are shown, for example, if I click on Title1 - Text1, Text2, Text3, and Text4 are shown also, instead of the only Text1.
this is link to my codesandbox example
My code:
 import React, { useState } from "react";
import "./styles.css";

const data = [
  {
    id: "services",
    key: "1",
    title: "Title1",
    text: "Text1."
  },
  {
    id: "services",
    key: "2",
    title: "Title2",
    text: "Text2."
  },
  {
    id: "services",
    key: "3",
    title: "Title3",
    text: "Text3."
  },
  {
    id: "services",
    key: "4",
    title: "Title4",
    text: "Text4"
  }
];

export default function App() {
  const [toggled, toggle] = useState(true);
  return (
    <div className="App">
      {data.map(({ title, text }) => {
        return (
          <>
            <h1 onClick={() => toggle(toggled => !toggled)}>{title} </h1>
            {!toggled ? (
              <>
                <p>{text}</p>
              </>
            ) : null}
          </>
        );
      })}
    </div>
  );
}

What I want to do is when the user clicks on Title1, only Text1 to appear, not all other Texts. Any suggestions are greatly appreciated,
Thank you.

A:

Instead of storing the boolean values of true/false in your component's toggled state, you can store the key from the data array instead.
Then, you can conditionally render the text below h1 based on the current toggled state
export default function App() {
  const [toggled, toggle] = useState("");
  return (
    <div className="App">
      {data.map(({ title, text, key }) => {
        return (
          <>
            <h1 onClick={() => toggle(key)}>{title} </h1>
            {toggled ===key ? (
              <>
                <p>{text}</p>
              </>
            ) : null}
          </>
        );
      })}
    </div>
  );
}

I have forked your demo here.

