0

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"
      }}
      onMouseOver={(e) => handleBoxToggle(e)}
    >
      {children}
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <button onMouseOver={() => 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).

Germán
  • 1,007
  • 1
  • 7
  • 20

2 Answers2

0

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

Pass it like this onMouseOver={handleBoxToggle}

Rusty Nail
  • 120
  • 1
  • 7
  • I did a simple example to post it here, but in my main App, it doesn't work, nothing happens. I'm calling on component A the Component B which uses Component C as child. – Germán Aug 26 '22 at 14:04
  • Can you show how you passed your function to `onMouseOver` in main App? Did you understand what I meant in answer above? – Rusty Nail Aug 26 '22 at 14:15
  • Still not my main app (it is too much code for a simple example) but please refer to the code sandbox above to see updated doubt. Thank you! – Germán Aug 26 '22 at 14:21
  • @Germán check please [codesandbox](https://codesandbox.io/s/friendly-butterfly-2zzxp4?file=/src/App.js). I hope that's what you meant – Rusty Nail Aug 26 '22 at 14:23
  • Please Refer to my updated CodeSandBox on top to check the current doubt. – Germán Aug 26 '22 at 14:26
  • I [forked your sandbox](https://codesandbox.io/s/withered-lake-u2xb84?file=/src/App.js) check please. You should pass your event named `e` to `handleBoxToggle` as its argument. `blue !important` doesn't work because you should remove `!important` – Rusty Nail Aug 26 '22 at 14:36
  • I deleted important and it works now. I don't actually get why, but it works. I'll close this question if you want to post your answer. Thank you. – Germán Aug 26 '22 at 14:46
  • https://stackoverflow.com/questions/462537/overriding-important-style – Rusty Nail Aug 26 '22 at 14:47
0

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()}
Ramkumar G
  • 415
  • 1
  • 8