I am trying to inline toggle the background color of the submit button with react and state. I am aware that this can be achieved through a bool value isMouseOver ? "black" : "white" in style. But I wonder why my first attempt does not work? Even though the variable myColor has been changed by my mouse action:
isMouseOver ? "black" : "white"
myColor
import React, { useState } from "react"; function App() { const [myColor, setColor] = useState("white"); function toggleColor() { if (myColor === "black") { setColor("white"); } else { setColor("black"); } console.log("mycolor", myColor); } return ( <div className="container"> <h1>{myColor}</h1> <input type="text" placeholder="What's your name?" /> <button style={{ backgroundColor: { myColor } }} onMouseOver={toggleColor} onMouseOut={toggleColor} > Submit </button> </div> ); } export default App;
just change this line i.e remove the curly braces around myColor, it should working fine
style={{ backgroundColor: { myColor } }}
to
style={{ backgroundColor: myColor }}
2.1m questions
2.1m answers
60 comments
57.0k users