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?
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>
))}
</>
);
};