I am trying to render an array using the map() function while giving each element its own unique className (based on the index value) using some established states. An element should change colour when clicked using hooks. I've run into a problem where className = {"header" + {index}.index} gives the correct state name (header0, header1, etc.) but corresponds to a string rather than the class names established with the same names.
const data = ["James", "John", "Jessica", "Jamie"];
export default function App() {
const [header0, setHeader0] = useState("visable");
const [header1, setHeader1] = useState("visable");
const [header2, setHeader2] = useState("visable");
const [header3, setHeader3] = useState("visable");
const clicked = (index) => {
if (index === 0) {
setHeader0("invisible");
} else if (index === 1) {
setHeader1("invisible");
}
/*Is there an alternative like {setHeader + index} instead of this loop?*/
};
return (
<div className="App">
<h1>Sample Project</h1>
{data.map((value, index) => (
<h1
className={"header" + { index }.index}
onClick={() => {
clicked(index);
}}
>
{/* classname should be the state "header0" but right now its just a string */}
Hello {value}!
</h1>
))}
</div>
);
}
Here is a code sandbox of what I am trying, with a few comments where things are going wrong. Am I going about this problem the correct way? https://codesandbox.io/s/wispy-star-38qvw?fontsize=14&hidenavigation=1&theme=dark
Any help is greatly appreciated!