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.