My code below: I am learning ReactJS. Trying to change the background colour of the button on mouse hover. I know css:hover is the easiest approach. But doing this implementation to learn.
It works fine if I check the 'hover' value using if else condition. But it gives the error "TypeError
Cannot assign to read only property 'backgroundColor' of object '#'" when I try to set the background colour inside the onMouseEnter and onMouseLeave event handler functions.
What is the read-only property here? I have not made it const. Is it read-only by default? How do I override it?
import React, { useState } from "react";
function App() {
let [ hover, setState] = useState(false);
let buttonStyle = {
backgroundColor:''
}
function hoverActive(){
setState(true);
buttonStyle.backgroundColor='black';
}
function hoverInactive(){
setState(false);
buttonStyle.backgroundColor='';
}
if(hover){
//buttonStyle.backgroundColor='black';
}
else{
//buttonStyle.backgroundColor='';
}
return (
<div className="container">
<h1>Hello</h1>
<input type="text" placeholder="What's your name?" />
<button style={buttonStyle} onMouseEnter={hoverActive} onMouseLeave={hoverInactive}>Submit</button>
</div>
);
}
export default App;