passing props to routes in react-router 2.4 - reactjs

I would like to pass in some props from the router to the components
Something like this:
<Route component={Foo} some_prop={12}/>
Is there any way to do this with the latest react-router? I know it was not possible (without using a wrapper) pre 1.0.

If you're passing them directly to the <Route /> component like that, it's now possible to do it exactly the way you're suggesting:
<Route foo="bar" />
Will give you access to the foo prop on this.props.route.foo
Via: https://github.com/reactjs/react-router/blob/master/docs/Troubleshooting.md#passing-additional-values-into-route-components
As a side note: if you're using something higher level like <RouterContext /> it is still necessary to use a data wrapper component of some kind, unfortunately.

Related

Is this a good alternative to react-redux?

I don't want to use redux because there's too much boilerplate. So I am looking for a way to share a global state between components. Is it ok to pass the whole state of the App (root) component?
I have no issue with it so far but there must be a hole down the road, is there?
<HashRouter>
<App />
</HashRouter>
<Switch>
<Route exact path='/' render={props => <TheListForm appState={this.state} app={this} />} />
<Route exact path='/myvideos' render={props => <MyVideos appState={this.state} app={this} />} />
</Switch>
So in my child components I have "this.props.appState" which contains the equivalent of the redux store and I can update it simply by doing:
this.props.app.setState({name:"bob"});
If you want a smaller, with less boilerplate and with a lower learning curve state management library, you could check out mobx. You want to use a state management library, if you component exceeds more than a few child component, because your app will rerender everything on every change. With this.props.appData.setState and a form your while app would rerender if the user types something. It also breaks the react one way data flow concept.
Imagine that you build a large scale project and there are so many hierarchies.
A includes B, B to C, ..., Y to Z.
If you want to pass the props from A to Z, you must set properties of all components from B-Z.
In that case, Redux is very useful and you only correct 2 components A and Z.
And also you can implement the bi-directional data flow with Redux.
https://rootzjs.org/ you should give it a try with this one. dead easy to use.

Can react router have a route with multiple option parameters where (e.g.) both are required, or none

Using react-router-dom I have a route like so:
<Route path='/:year?/:month?' component={ThingUsingYearAndMonth} />
But really I want BOTH year and month to exist (e.g. /2018/Dec or /2017/Jan) or neither. I.e. just /2018 wouldn't match
I would probably handle that using two routes -- one for when both are provided and one for when neither are provided:
<Route path='/:year/:month' component={ThingUsingYearAndMonth} />
<Route path='/' exact component={ThingUsingYearAndMonth} />
Try providing explicit parameters with regex:
<Route path='/:year(\\d{4})?/:month([A-Za-z]+)?' component={ThingUsingYearAndMonth} />
I don't think there is any mechanism provided by the react-router-dom to validate the route params. You are better off creating your own Higher Order Component and validate the route params in it. Or you can use regex to validate your params in the route itself.

How do I avoid rendering a component when another component in a similar path has already rendered when using URL params in React Router v4?

I'm trying to create RESTful routes for my application, but I'm having problems when it comes to routes with URL params.
Here are the routes that I want to have:
/accounts
/accounts/new
/accounts/edit
/accounts/:id
These is what my router looks like:
<Router>
<Route exact path="/accounts" component={AccountsList} />
<Route exact path="/accounts/new" component={AccountCreate} />
<Route exact path="/accounts/edit" component={AccountUpdate} />
<Route exact path="/accounts/:id" component={AccountDetail} />
</Router>
/accounts works fine, but when I go to /accounts/new or /accounts/edit, it also renders AccountDetail which is supposed to be located at /accounts/:id.
For the record, that I get that this is the correct behavior since /accounts/:id technically matches /accounts/new and /accounts/edit.
My question is if there's a way to make :id match with a specific pattern only (numbers only).
Try the < Switch> component of reactRouter.
Renders the first child < Route> or < Redirect> that matches the
location.
I think it's exactly what you are looking for.

ReactJS Values In The URL Always Visible

I have a filter system for my products in ReactJS which basically has the following:
http://localhost:3000/category/women/subcategory/tops/sorting/null/price/null/size/null/color/null/brands/null/merchants/null
The Route is as follows:
<Router>
<Route path="/category/:cat/subcategory/:subCat/sorting/:sorting/price/:price/size/:size/color/:color/brands/:brands/merchants/:merchants" component={Products} />
</Router>
The Problem is that I want to show filters in the URL in when they have a value other than null. Current my component works but I have to display every single filter in the URL with a null value by default, this is causing my URL to be extremely long. The only way I thought possible was to do a permutation combination of all the possible URLs in the filter and direct them all to { Products } which is extremely silly. There must be something in the Router component that I'm missing?
You need to use optional params in this case.
As and example if you want to accept both sorting/ascending/price and sorting/price you can write your path as follows assuming you use react router v4.
<Router>
<Route path="sorting/:sort?/price" component={Products} />
</Router>
You can read more about this here: React Router with optional path parameter

Unit testing route matching with React Router 2

I’m trying to add unit tests for a React application and would like to test the routes provided by React Router (2.0.1). I’d like to test whether specific paths that I supply will match a route. I am writing my tests using Mocha and expect.
I’ve looked through the documentation on the React Router repository, but the only testing guide I could see was explaining how to test a <Link /> and how it’s rendered.
Say I have the following code:
// import statements omitted for brevity
export const routes = (
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/foo">
<IndexRoute component={FooIndex} />
<Route path="add" component={FooAdd} />
<Route path=":fooId" component={FooDetails} />
</Route>
</Route>
)
ReactDOM.render(
<Router history={browserHistory}>{routes}</Router>,
document.getElementById('app')
)
How can I test that the routes created in the routes variable would match the following:
/
/foo
/foo/add
/foo/25
But not routes like:
/foo/bar/12
/bar
Essentially I want to check that every expected URL format has a route that will match it and that unexpected URLs don't match any routes.
I’m not interested in the elements that are rendered by the routes, so don't want to base my tests on checking whether a specific thing is rendered, only that a matching route was found and preferably some way of checking that it was in fact the expected route (I'd guess checking what the name of the component is or something?)
Any help is gratefully appreciated.
Thanks
We test exactly this in our test for matchRoutes: https://github.com/ReactTraining/react-router/blob/v3/modules/__tests__/matchRoutes-test.js
You can follow this pattern. If you can't identify your routes by reference, you can indeed assert on the components that were rendered as well.
As matchRoutes isn't exported, you'll want to use the match helper (otherwise used for for server-side rendering) instead, and check renderProps.routes or renderProps.components.

Resources