Ben
Ben

Reputation: 3

How to send props to children in React Router v4?

I have to use fetch in children component, but I don't know how to send props in Route. Is there any option for doing that or do I have to do it some other way?

This is route in my parent component:

<Route path={`/beers/:beerId`} component={Beer}/>

Then I'd like to use fetch in children component:

    fetchData = () => {
    let url = `https://api.punkapi.com/v2/beers/${this.props.id}`;
    fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
        this.setState({
            data: data
        })
    );
};

Upvotes: 0

Views: 552

Answers (3)

frogatto
frogatto

Reputation: 29285

When a Route matches, it will inject three props to the component it holds:

  • location: Information about the current location.
  • history: Access to the browser history and methods to navigate through.
  • match: All matched URL parameters.

So, in your Beer component you can access the URL param beerId using match.params.beerId, and your Ajax call:

const {beerId} = this.props.match.params;

fetchData = () => {
    let url = `https://api.punkapi.com/v2/beers/${beerId}`;
    fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
        this.setState({
            data: data
        })
    );    
}   

Upvotes: 2

Muljayan
Muljayan

Reputation: 3886

If you are looking to get the beerId from the URL.You can get it from this.props.match.params.beerId.

You can also pass it directly the traditional way using the render method

<Route path={`/beers/:beerId`} render={()=><Beer id={YOURID}/>}/>

If you're using the render method you can access the id using this.props.id. But since you already have the beer id in the URL its best if you get it using this.props.match.params.beerId.

Upvotes: 1

Dimitris Damilos
Dimitris Damilos

Reputation: 2438

You need to use the render attribute of the route. An example would be:

<Route path={`/beers/:beerId`} render={(props) => <Beer {...props} beerList={beerList} />} />

where beerList is a hypothetical function or variable which is passed as a prop down to to <Beer /> component.

Further info: A Simple React Router v4 Tutorial

Upvotes: 0

Related Questions