C
C
CHtommy2021-09-25 19:31:34
React
CHtommy, 2021-09-25 19:31:34

How to make different states for useContext objects?

Such a question, I have a const :

const [hovered, setHovered] = useState(false);
    const toggleHover = () => setHovered(!hovered);

As soon as you use this in the parent component, then all objects have a hover, while the active one becomes the one that the mouse was hovered over.
As soon as this component becomes a child and const remains in the parent component, then everything breaks down and at the output I have hover on all elements, regardless of where the mouse is hovered (on any of the elements) (I output through props).
I was advised to give the parent element a useContext and expose it in the child, but the effect is the same.
How to give child component different states in elements? I don't understand how to interact...

upd: useContext and generally hovered works like firing className if hovered == true.
I immediately say that I am not very "skillful" in the front and I have already googled hooks in react, etc., etc., but apparently it does not reach me ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
antares4045, 2021-09-25
@CHtommy

Perhaps I misunderstood you, but apparently it's not about setState, and useContext will not help here: you are trying in a boolean variable (which simply contains either "yes" or "no") data on which element hovered by the user.
Not much tinkering with your structure, I can suggest that you create separate states for each child component in your parent component and forward them accordingly.
Although it’s better to learn how to use the useReduce hook (to store all information about hovers in one state)
UPD: I sketched out the code that answers the original question , only the context in it is really superfluous: it would be enough to implement the reducer at the root and forward the wrappers around it with props.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question