I am having a songKey array as a STATE. Its data populates from API. I am rendering JSX using this array data. I like to add useRef in order to refer elements from the JSX. Is it possible to add useRef hooks via code automatically ? or shall I use document.getElementById() function to refer elements ?
const [songKey, songKeyController] = useState([]);
...
...
...
...
...
const renderLyrics = () => {
let lyrics = [];
if (songKey) {
lyrics = songKey.map((key) => (
<div key={key} className={`lyrics_container ${key}`}>
<div className="lyrics_data tamil-font">
{props.currentSong.Data[key]}
</div>
</div>
));
}
return lyrics;
};
I dont recommend using dom elements directly in React but if you are using it anyways then you can do it in way
use useRef in parent element then simply use querySelectorAll then use childs with index value of that array to access them directly
see the Example
main.jsx
import React, { useEffect, useRef, useState } from "react";
export default function Main() {
const EL = useRef(null);
const [data, setData] = useState(["First", "Second", "Third", "Fourth"]);
useEffect(() => {
const childs = EL.current.querySelectorAll(".child");
// fun demo
let index = 0;
setInterval(() => {
const curr = childs[index % childs.length];
childs.forEach((each) => (each.style.background = ""));
curr.style.background = "red";
console.log(curr);
index++;
}, 1000);
// fun demo
}, [data]);
return (
<div className="root" ref={EL}>
{data.map((each, i) => {
return (
<div className="child" key={i}>
{each}
</div>
);
})}
</div>
);
}