1

I'm trying to set up multiple useStates on dynamically created elements inside an array.map. Every element inside of the array.map should use the same useState, but have its proper value assigned. For example the array.map has 3 different elements, which all should have "focus" set to false. When clicked, the clicked element's useState should change to true, the others should remain false.

    const [focus, setFocus] = useState(false);
    { projects.map((project, index) => (
        <div className={` ${focus ? "focus" : ""} `} key={project.id}>
            <div className="cover" to={"/work/" + project.slug} onClick={ () => setFocus(true) }>
            </div>
        </div>
    ))}
1

1 Answer 1

1

You need to store the id of the project that should have the focus. A single boolean state property isn't going to work.

e.g.

const [focusedProject, setFocusedProject] = useState(undefined);
...
onClick={() => setFocusedProject(project.id)}

then

<div className={` ${focusedProject === project.id ? "focus" : ""} `} key={project.id}>
Sign up to request clarification or add additional context in comments.

3 Comments

Ah sure, that's a really logical way of doing it. Thanks a lot!
You could change the className value to {project.id == focusedProject && "focus"} instead of using an ternary operator. There is also no need to nest the expression inside an string template.
yes thats true, but when needed to add more class names in the future, without the likes of classnames library etc, most people turn to template literal strings, as in the original question, and in that case {project.id == focusedProject && "focus"} outputs 'false' as one of the class names, which isn't ideal

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.