Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda