'Dynamically add html elements in react
Please how can I dynamically add html element (like span) to elements in a react component. I want to implement something like this
let text1 = '"Text one sentence.';
let text2 = 'Text two sentence';
const textElement1 = document.querySelector(".text-1");
const textElement2 = document.querySelector(".text-2");
let textSpan;
function setText(t) {
t == text1 ? (textElement1.innerHTML = "") : (textElement2.innerHTML = "");
t.split("").map((x) => {
let charElement = document.createElement("span");
let charNode = document.createTextNode(x);
charElement.appendChild(charNode);
t == text1
? textElement1.appendChild(charElement)
: textElement2.appendChild(charElement);
});
textSpan = document.querySelectorAll("span");
}
function setFontWeight() {
textSpan.forEach((element) => {
let position = element.getBoundingClientRect();
// Calculate The Distance Between Cursor And Target Elements
let distance = Math.ceil(
Math.sqrt((position.x - pointerX) ** 2 + (position.y - pointerY) ** 2)
);
// The Longer The Distance The Lower The Font Weight
element.setAttribute(
"style",
`font-variation-settings: 'wght' ${900 - distance * 2};`
);
});
}
This is the react component I have created
function TopSidePane(){
return(
<div onMouseMove={(e)=>Hover(e)} className="top-side-pane">
<div className="text-container">
<h1 className="text-1">{text1}</h1>
<h1 className="text-2"> {text2}</h1>
</div>
<div className="custom-pointer" ></div>
</div>
);
}
Anytime there is a mouse movement on the component (if it get to the text inside the component) I want to be able to add span elements to the elements with the class names 'text-1' and 'text-2'. After I add the elements, I call the setFontWeight to make the weight of the hovered letters bold.
Please any help on how to implement this in react. I am new to react.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
