Kalpesh Prithyani
Kalpesh Prithyani

Reputation: 35

Adding a css class in React through event handlers

I was trying to add a css class on mouse over just as mentioned in the react documentation but I am not sure why it is not working. Please help

index.js:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  let className = "";
  return (
    <div className="App">
      <h1
        className={className}
        onMouseOver={() => {
          if (!className.includes("colorRed")) {
            className += " colorRed";
          }
        }}
      >
        Hello CodeSandbox
      </h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

style.css

.App {
  font-family: sans-serif;
  text-align: center;
}

.colorRed{
  color:red;
}

Link: https://codesandbox.io/s/xjx72w5kkw?fontsize=14

Upvotes: 1

Views: 939

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 53991

This issue here is that you're mutating the className variable but this alone doesn't cause React to re-render your component.

You'll need to store the className in the state so that when you change it, React knows to re-render your component.

Here's a version of your sandbox making use of state: https://codesandbox.io/s/m51qoq72pp

// First we're importing useState from react
// This is part of the new Hooks mechanism 
// More about hooks: https://reactjs.org/docs/hooks-intro.html
// You could also use a class and this.setState instead
import React, { useState } from "react";

// Then we set up our piece of state
const [className, setClassName] = useState("");

// Your event now uses setState
onMouseOver={() => {
  if (!className.includes("colorRed")) {
   setClassName(current => current + " colorRed");
  }
}}

Upvotes: 1

Related Questions