Is it possible to use useState to change the background color of :hover?
Answered
noli posted this in #help-forum
noliOP
if i have const [colorS, setcolorS] = useState("#000000")
how do i make it so the colorS is the :hover background color of a div?
how do i make it so the colorS is the :hover background color of a div?
18 Replies
Just do it using css?
noliOP
how do i connect :hover in .css to the state in .js?
thats what im confused about
Whenever a div is hovered, it automatically applied any css marked with :hover
div { background: red; }
div:hover { background: yellow }
div:hover { background: yellow }
That's basic css
noliOP
i know that but
i want the user to be able to use hex codes to change the div:hover background color
so i put it in a state
Then you would need to set the new hex code. Use inline style for this and do setColor() on whatever you are using to change hex
noliOP
you can do inline :hover ?
Use onMouseEnter and onMouseLeave event on div
Answer
noliOP
did it but on
onMouseOver={`this.style.color=${colorS}`}
it gives Error: Expected onMouseOver listener to be a function, instead got a value of
stringtype.
Ashy Storm-Petrel
you have to access the element itself by accessing the
event.target
or event.currentTarget
noliOP
did it without ` and im getting TypeError: Cannot read properties of undefined (reading 'style')
let me try that
worked! thank you
(e) => e.target.style.background=colorS