Search code examples
reactjscomponentsreach-router

How to pass state to Link from reach-router


UPDATED CODE STILL NOT WORKING

Haven't been able to find an answer on here to help with my problem.

In my Playlist component, I have an image that links to a new path for tracks. I want to pass a Playlist ID to the track so it can display tracks based on the ID it is given but no matter how I do this it wont work for me.

My Playlist Component returns:

 <Link to = '/tracks' state = {{playlist:playlist.id}}>
   <img alt = "album"src={playlist.images.url}/>
 </Link>

In my Track Component, it is doing the following:

export default class Tracks extends React.Component {
    constructor() {
        super();
        this.state = {
            playlistid: 0
        };
    }
        componentDidMount() {
            this.setState({
                playlistid: this.props.location.state.playlistid
            });
    }
    render() {
        return (
            <div>
                <p>PlaylistID: {this.state.playlistid}</p>
            </div>
        );
    }
}

Can anyone tell me which Component is wrong? Sorry I'm still quite new to React

Thanks


Solution

  • In order for you to pass on a state to Link component from Reach router, you can pass on state as a separate prop. The to prop neeeds to be a string

    <Link
         to='/tracks'
         state= {{
            playlistid: playlist.id
         }}
     >
         <img alt = "album"src={image.url}/>
     </Link>
    

    For more information refer to the documentation of Link from Reach-router

    EDIT:

    The way you have implemented the Link component works with react-router Link component