I have a component and three div tag's in it. In one of the div
tag, I created onMouseOver
event and trying to change color of text onMouseOver
.
React onMouseOver
, onMouseEnter
events and style are changing dynamically in React.
import React from 'react'
function Middle() {
const styles = {
'text-align': 'center',
'padding': '30px',
}
function myName() {
styles.color = "green"
}
function noName() {
}
return (
<div className="middle">
<div id="cspace" style={styles} onMouseEnter={myName} onMouseLeave={noName}>
<h1>Hello World</h1>
</div>
</div>
)
}
export default Middle
I am expecting the color of text in div to be changed. the output I am getting is:
"Cannot add property color, object is not extensible"
For a functional component, this is a good scenario to use useState
hook to store the color
value.
function App() {
const [color, setColor] = React.useState("");
const styles = {
"text-align": "center",
padding: "30px",
color: color
};
return (
<div className="middle">
<div
id="cspace"
style={styles}
onMouseEnter={() => setColor("green")}
onMouseLeave={() => setColor("")}
>
<h1>Hello World</h1>
</div>
</div>
);
}
See CodeSandbox
you can do this using css only. try this.
#cspace:hover{color:red;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With