0
clickMusicHandler() {

    //console.log(this.props.channel);

    axios.put('/channels/'+'test', {

        playList: {
            songName: this.props.track.name,
            artist: this.props.track.artists[0].name,
            url: this.props.track.preview_url
        }
    })
        .then((res)=>{

            //set state

        console.log("added song");
    }).catch((err)=>{
        console.log(err);
    });   

}

In my component called SongList I want to pass in a this.props.track.preview_url to a different component that uses this component when an item of the component SongList is clicked. The code above is a click handler for a SongList item.

I want to add this.props.track.preview_url to a local array of the component that is using this component.

In the component that is using SongList it looks like :

    const mapToComponents = (data) => {

        if(this.state.keyword == '') return [];

        return data.map((eachData, index) => {
            return (  <SongList track = { eachData } key={ index }/>  );
        });
    };

How can I add the url of the clicked item of SongList to a local array called this.testSongList = []; of the component using SongList?

Dawn17
  • 7,825
  • 16
  • 57
  • 118

1 Answers1

0

This question addresses how to pass data from a child component to its parent: How to pass data from child component to its parent in ReactJS?

In your case, you would pass the clickMusicHandler as a prop to SongList, which updates the parent component.

However, if you would like the state to be consistent across multiple components, I suggest using Redux. Redux is a JS state container which allows you to bind props to state variables. When you run the click handler, dispatch the new preview_url to the store, and your other component will automatically re-render with the new value.

Getting Started with Redux

iamttc
  • 1
  • 1