Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Can I use document.getElementByID in React

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;
  };
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!