Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router - how to use route params in onEnter?

Tags:

react-router

I want to do a fetch using the onEnter callback, but I don't know how to read a URL param in the Route component. I have this Route

<Route path="book/:bookId" component={BookContainer} onEnter={onBookLoad()}/>

I want to use the bookId from path as function parameter for onBookLoad(). Is it possible?

like image 706
vicusbass Avatar asked May 13 '16 14:05

vicusbass


People also ask

How do we define route with URL parameters in react?

Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.

How do you pass additional data while redirecting to a route in react?

Using Link So when we click on the Register link, it will redirect to the /register route. But Link also allows us to pass additional data while redirecting. Here, at the place of data_you_need_to_pass , we can pass a string or object , array and so on and in the /register route we will get that data in props.


1 Answers

Nevermind, it was trivial.

<Route path="book/:bookId" component={BookContainer} onEnter={onBookLoad}/>

export function onBookLoad(nextState) {
 console.log(nextState.params.bookId);
 //do stuff with the param
}
like image 108
vicusbass Avatar answered Oct 03 '22 04:10

vicusbass