Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

308
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda