Home > Software design >  Passing an img src from the ParentComponent to the ChildComponent using an img onClick event
Passing an img src from the ParentComponent to the ChildComponent using an img onClick event

Time:01-28

Im trying to pass the img src when the img below is clicked and pass from the ParentComponent to the ChildComponent

    inside ParentComponent.js


      const [LoadMoreVideos, setLoadMoreVideos] = useState([]);

            LoadMoreVideos.push(
                <img
                  className="m-4 mx-auto hover:cursor-pointer "
                  width="280"
                  height="160"
                  src={`${fetchData.videos[i].thumbnail}`}
                  key={LoadMoreVideos}
                  onClick={ChildComponent}
                ></img>
              );
        
<ChildComponent  /> 


**inside ChildComponent.js**

 > **im trying to console.log the src but im getting undefined**

     const ChildComponent = (props, e) => {
     console.log(e.target.src)
     }

CodePudding user response:

If I get your question correctly, you're trying to pass the src of the clicked image to the child component. In this case pass an src prop to the child, this src is a state in the parent. And the handler of the click on image in the parent should modify the state of src with the new one.

Something like this:

//inside ParentComponent.js

const ParentComponent = () => {
    const [LoadMoreVideos, setLoadMoreVideos] = useState([]);
    const [srcValue, setSrcValue] = useState(''); // The state of src that we handle in the parent component

    function handleClick(e) {
      setSrcValue(e.target.src); //setting the srcValue to the new src that we get from the event)
    }

    //...

    LoadMoreVideos.push(
      <img
        className="m-4 mx-auto hover:cursor-pointer "
        width="280"
        height="160"
        src={`${fetchData.videos[i].thumbnail}`}
        key={LoadMoreVideos}
        onClick={handleClick}
      ></img>
    );
    //Notice the handler is handleClick that changes the state of srcValue

    //...
    return (
        //...
        <ChildComponent src={srcValue} /> // Here we pass the srcValue to the child
        //...
    )
}
  • Related