Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change style on MouseOver event in reactJS, functional component

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"

like image 747
Krishna M Avatar asked Dec 31 '22 15:12

Krishna M


2 Answers

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

like image 116
Joseph D. Avatar answered Jan 03 '23 04:01

Joseph D.


you can do this using css only. try this.

#cspace:hover{color:red;}
like image 20
Sumit Patel Avatar answered Jan 03 '23 04:01

Sumit Patel