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

177
Vistas
Run Javascript in React after inserting elements

I'm kinda new to React, I am trying to make a website that makes a request to my server using fetch which will return youtube videos related to what the user searched and then it will add the content in the DOM.

The way I do it right now is this:

const handleSearchSubmit = (e) => {
    e.preventDefault();
    const videosList = document.getElementById("videos");
    videosList.innerHTML = "";
    setIsPending(true);
    setError("");

    fetch(`http://localhost:8000/api?video=${searchTerm}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        data.forEach((video) => {
          const div = document.createElement("div");
          div.classList.add("searched-video");
          div.innerHTML = `
          <img src="${video.thumbnail.thumbnails[0].url}">
          <h3>${video.title}</h3>
          <button>Copy Link</button>
          `;
          videosList.appendChild(div);
        });
        // console.log(data);
        setIsPending(false);
      });
  };

I would like to make it so when the users click the button which says "Copy Link" to copy the video id which is stored in video.id but i cannot add a "onclick={}" attribute to the button so how would I run the code?

Any idea?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In react, it's a really bad idea to manually manipulate the DOM like that. You should pretty much never be using things like getElementById, createElement, appendChild.

What you probably want to do is have a state for your videos, then you can render that list via a proper react component. That also makes dealing with your onClick event easier. Here's a rough sketch of what that might look like, based on your code:

const MyElement = () => {
  const [videos, setVideos] = useState([]);
  const getVideos = e => {
    fetch(`http://localhost:8000/api?video=${searchTerm}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then(response => {
        return response.json();
      })
      .then(data => {
        setVideos(data);
      });
  };
  const copyLink = (e, video) => {
    // code to copy link from video
  };
  return (
    <>
      <button onClick={getVideos}>Click to fetch</button>
      {videos.map(video => (
        <div className="searched-video">
          <img src={video.thumbnail.thumbnails[0].url}/>
          <h3>{video.title}</h3>
          <button onClick={e=> copyLink(e, video)}>Copy Link</button>
        </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