I'm trying to change the background color of a button to black as mouse hover over it and change it back to white when it's not. I used the state on a string which will change to black or white and pass it in style property. Any idea on where I'm going wrong?
Thank you.
import React, { useState } from "react";
function App() {
const [headingText, setHeadingText] = useState("Hello");
const [buttonColor, setButtonColor] = useState("White"); //setting the state
function handleClick() {
setHeadingText("Submitted");
}
function mouseOver() {
setButtonColor("Black"); //changing state
}
function mouseOut() {
setButtonColor("White"); //changing state
}
return (
<div className="container">
<h1>{headingText}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { buttonColor } }} //where I want it to apply
onClick={handleClick}
onMouseOver={mouseOver}
onMouseOut={mouseOut}
>
Submit
</button>
</div>
);
}
You should use instead onMouseEnter
and onMouseLeave
events.
Try as the following:
<button style={{ backgroundColor: buttonColor }}
onClick={handleClick}
onMouseEnter={mouseOver}
onMouseLeave={mouseOut} >
Read further here in React documentation for Mouse Events .
I hope this helps!
import React, { useState } from "react";
import { debounce } from 'lodash';
function App() {
const [headingText, setHeadingText] = useState("Hello");
const [buttonColor, setButtonColor] = useState("White"); //setting the state
function handleClick() {
setHeadingText("Submitted");
}
function mouseOver() {
setButtonColor("Black"); //changing state
}
function mouseOut() {
setButtonColor("White"); //changing state
}
return (
<div className="container">
<h1>{headingText}</h1>
<input type="text" placeholder="What's your name?" />
<button
style={{ backgroundColor: { buttonColor } }} //where I want it to apply
onClick={handleClick}
onMouseOver={debounce(mouseOver, 200)}
onMouseOut={debounce(mouseOut, 200)}
>
Submit
</button>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.