Ivan
Ivan

Reputation: 380

How do I pass specific id to route's path?

I am emitting action to redux store and trying to get movie id from the store but Movie component fails to render. I assume it is wrong approach to do this. What would be a right way to pass movie id to route's path?

main component

render() {
return (
    <BrowserRouter>
        <div>
            <Route exact path="/" component={PopularList} />
            <Route path={`/${this.props.movieId`} component={Movie} /> 
        </div>
    </BrowserRouter>
)

}

component from which I want to get the link Link to={/${movie.id}}

render(){
if (this.props.popularMovies.length) {
        return (
            <section className={"movies"}>
                <h3>Popular Movies</h3>
                <h4>{this.props.popularMovies.length}</h4>
                <div className={"movies__block"}>
                    {
                        this.props.popularMovies.map((movie) => {
                            return (
                                <Link to={`/${movie.id}`} component={Movie} key={movie.id} onClick={() => {this.getMovieId(movie.id)}}>
                                    <div className={"movie-card"}>
                                        <div>{movie.title}</div>
                                        <img src={`${this.dbLink}${movie.poster_path}`}></img>
                                    </div>
                                </Link>
                            )
                        })
                    }
                </div>
            </section>
        )
    }
}

Upvotes: 0

Views: 177

Answers (1)

Colin Ricardo
Colin Ricardo

Reputation: 17249

If you're passing a parameter, you can use the link like:

<Route path='/route/:id' exact component={MyComponent} />

and then in MyComponent you can access with:

const { id } = props.match.params;

Otherwise, you can pass like:

<Link to={{ pathname: '/route', state: { foo: 'bar'} }}>My route</Link>

Then access it with:

const { foo } = props.location.state;

Upvotes: 1

Related Questions