Reputation: 146
I would like to get some advise from you guys, how can I prepend html element when the event listener listen I mouse enter to the container area. I am using ReactJS to build my frontend. I encounter an issue as I cannot prepend the html element by using the event target which is provided by the callback of the event listener. I have included my code snippet as below:
box.addEventListener("mouseleave", function (evt) {
evt.target.style.border = "unset";
});
box.addEventListener("mouseenter", function (evt) {
evt.target.style.border = "1px solid red";
var div = document.createElement("div");
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
evt.target.parentNode.insertBefore(evt.target,div);
});
In fact, I would like to prepend below div to the container parent whenever I mouseenter the div container.
I really appreciate your contribution.
Upvotes: 0
Views: 65
Reputation: 6724
Unfortunately they way you are trying is not the react way.
You need to use state and if statements in your code with React way.
Here is a sample for you:
https://codesandbox.io/s/distracted-tree-1fpjnr
import { useState } from "react";
import "./styles.css";
export default function App() {
const [isShowDiv, setIsShowDiv] = useState(false);
return (
<div
className="App"
onMouseLeave={() => setIsShowDiv(false)}
onMouseEnter={() => setIsShowDiv(true)}
>
{isShowDiv && (
<div style={{ background: "red", height: "50px", width: "100%" }}></div>
)}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Upvotes: 1