0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, marking your answer as correct, this is exactly what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.