Home > Back-end >  React, onMouseOver not working on child component but it does in button
React, onMouseOver not working on child component but it does in button

Time:08-27

Given the following code: -codesandbox-

import "./styles.css";
import React from "react";

const B = () => {
  return (
    <div>
      <C>C inside B</C>
    </div>
  );
};

const C = ({ children, estado = "lightgrey" }) => {
  const handleBoxToggle = (e) =>
    (e.target.style.backgroundColor = "blue !important");

  return (
    <div
      style={{
        backgroundColor: estado,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minWidth: "1rem",
        minHeight: "1rem",
        outline: "1px solid black"
      }}
      onm ouseOver={(e) => handleBoxToggle(e)}
    >
      {children}
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <button onm ouseOver={() => alert("hi")}>Alert on hover Button</button>
      <B></B>
      <C>Alert DIV estado</C>
    </div>
  );
}

Why does the button display the alert on mouse over but the component 'C' does not? Shouldn't it have the function integrated? How can I make the mouseover on 'C' Component work? (it will be created dinamically many times).

CodePudding user response:

You didn't call your function handleBoxToggle inside onMouseOver event callback

Pass it like this onMouseOver={handleBoxToggle}

CodePudding user response:

You need to call your funtion like

onMouseOver={handleBoxToggle}

OR if you want to pass any arguments to this funtion you can call like

onMouseOver={() => handleBoxToggle()}
  • Related