Next.js Discord

Discord Forum

Is it possible to use useState to change the background color of :hover?

Answered
noli posted this in #help-forum
Open in Discord
Avatar
if i have const [colorS, setcolorS] = useState("#000000")

how do i make it so the colorS is the :hover background color of a div?
Answered by <Milind ツ />
Use onMouseEnter and onMouseLeave event on div
View full answer

18 Replies

Avatar
Just do it using css?
Avatar
how do i connect :hover in .css to the state in .js?
thats what im confused about
Avatar
Whenever a div is hovered, it automatically applied any css marked with :hover
div { background: red; }
div:hover { background: yellow }
That's basic css
Avatar
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
Avatar
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
Avatar
you can do inline :hover ?
Avatar
Use onMouseEnter and onMouseLeave event on div
Answer
Avatar
did it but on
onMouseOver={`this.style.color=${colorS}`}
it gives Error: Expected onMouseOver listener to be a function, instead got a value ofstringtype.
Avatar
Ashy Storm-Petrel
you have to access the element itself by accessing the event.target or event.currentTarget
Avatar
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