1

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

5
  • Hi. Your example in codesanbox is.. "empty", it's just the base react template of codesandbox. Can you explain better your question and correct the example? Commented Mar 15, 2019 at 8:06
  • The link you shared has a standard template for a react project. Where is your code? Consider adding it here. Commented Mar 15, 2019 at 8:06
  • You are missing :hover in your class css decleration. You class should be .App:hover { font-family: sans-serif; text-align: center; } Commented Mar 15, 2019 at 8:08
  • are you expecting a solution like this stackblitz.com/edit/react-ubf5al ? Commented Mar 15, 2019 at 8:14
  • I am sorry (new to this :(), please check now Commented Mar 15, 2019 at 8:17

1 Answer 1

1

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");
  }
}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.