Nested Routes in React Router v4 - react-router

I'm trying to set up some nested routes to add a common layout. Check the code out:
<Router>
<Route component={Layout}>
<div>
<Route path='/abc' component={ABC} />
<Route path='/xyz' component={XYZ} />
</div>
</Route>
</Router>
While this works perfectly fine, I still get the warning:
Warning: You should not use <Route component> and <Route children> in the same
route; will be ignored

CESCO's answer renders first the component AppShell then one of the components inside Switch. But these components are NOT going to render inside AppShell, they will NOT be children of AppShell.
In v4 to wrap components you don't put anymore your Routes inside another Route, you put your Routes directly inside a component.
I.E : for the wrapper instead of <Route component={Layout}> you directly use <Layout>.
Full code :
<Router>
<Layout>
<Route path='/abc' component={ABC} />
<Route path='/xyz' component={XYZ} />
</Layout>
</Router>
The change is probably explained by the idea to make React Router v4 to be pure
React so you only use React elements like with any other React element.
EDIT : I removed the Switch component as it's not useful here. See when it's useful here.

You need to use the switch component to nesting to work nice. Also, see this question
// main app
<div>
// not setting a path prop, makes this always render
<Route component={AppShell}/>
<Switch>
<Route exact path="/" component={Login}/>
<Route path="/dashboard" component={AsyncDashboard(userAgent)}/>
<Route component={NoMatch}/>
</Switch>
</div>
And version-4 components do not take children, instead, you should use the render prop.
<Router>
<Route render={(props)=>{
return <div>Whatever</div>}>
</Route>
</Router>

Try:
<Router>
<Layout>
<Route path='/abc' component={ABC} />
<Route path='/xyz' component={XYZ} />
</Layout>
</Router>

If you do not want Layout to run at loaded. Use this method:
<div className="container">
<Route path="/main" component={ChatList}/>
<Switch>
<Route exact path="/" component={Start} />
<Route path="/main/single" component={SingleChat} />
<Route path="/main/group" component={GroupChat} />
<Route path="/login" component={Login} />
</Switch>
</div>
Whenever history changes, componentWillReceiveProps in the ChatList will run.

You can also try this :
<Route exact path="/Home"
render={props=>(
<div>
<Layout/>
<Archive/>
</div>
)}
/>

Related

react-router-dom switch not rendering components after dynamic path

I`ve been following an e-commerce tutorial and building on top of it. Im new to React and React Router Dom.
I've set a dynamic path for individual product pages, and now i' trying to add some new paths i.e. contact, about, etc.. If I add the new paths above the dynamic path they are rendered properly, but if I place the routes under the one with the dynamic path, for example the /hello, they won't render. Is this normal behaviour??
<Router>
<div>
<Navbar totalItems={cart.total_items} />
<Switch>
<Route exact path="/">
<Home products={products} handleAddToCart={handleAddToCart} fetchProduct={fetchProduct} />
</Route>
<Route exact path="/checkout">
<Checkout cart={cart} order={order} handleCaptureCheckout={handleCaptureCheckout} error={errorMessage} refreshCart={refreshCart} />
</Route>
<Route exact path="/cart">
<Cart
cart={cart}
handleUpdateCartQuantity={handleUpdateCartQuantity}
handleRemoveFromCart={handleRemoveFromCart}
handleEmptyCart={handleEmptyCart}
/>
</Route>
<Route exact path="/contact">
<Contact />
</Route>
<Route exact path="/:id">
<Details product={product} handleAddToCart={handleAddToCart} />
</Route>
<Route exact path="/hello">
<h1>Hello World</h1>
</Route>
</Switch>
</div>
<Router>
Yes, this behavior is completely normal, and expected. Recall that the Switch component "Renders the first child <Route> or <Redirect> that matches the location." This means that in the Switch component path order and specificity matter!
A path "/hello" is more specific than "/:id", so depending on route order may or may not be matched first. Or in other words, "/hello" can always be matched to "/:id", but not always the other way around.
You should always order the routes from more specific paths to less specific paths, and if done correctly there should be a near zero need for the exact prop.
"/hello" is more specific than "/:id" which is more specific than "/".
<Switch>
<Route path="/checkout">
<Checkout ... />
</Route>
<Route path="/cart">
<Cart ... />
</Route>
<Route path="/contact">
<Contact />
</Route>
<Route path="/hello">
<h1>Hello World</h1>
</Route>
<Route path="/:id">
<Details ... />
</Route>
<Route path="/">
<Home ... />
</Route>
</Switch>
If you had a nested "/contact/add" route for example, this is more specific than "/contact" and should be listed higher/before in the Switch.
Try removing the exact from the Route.
<Route exact path="/:id">
to:
<Route path="/:id">

Keep redux store values after redirecting to another page

When a user clicks a link it will guide the user to a checkout page.
selectSlot(slot){
window.location = `/checkout/${slot.target.value}`
}
My approach won't keep the redux store values.
How can I keep those values?
Here are the router definitions
<Provider store={store}>
<ConnectedRouter history={history}>
<Router>
<Switch>
<Route exact path="/" component={MainLayout} />
<Route exact path="/index.html" component={MainLayout} />
<Route path="/checkout" component={CheckoutLayout} />
<Route component={NotFound}/>
</Switch>
</Router>
</ConnectedRouter>
</Provider>
I am using Link from react-router-dom for the purpose and works for me. You can read about it here

Conditional rendering with React Router

I'd like to render some routes with a nav at the top, while rendering other routes (like a sign-up / sign-in page) without any nav.
For the setup with the nav, I have:
const App = () => (
<Router>
<div>
<Nav />
<div>
<Route exact path="/" component={Home} />
<Route path="/account" component={Account} />
<Route path="/news" component={News} />
</div>
<Footer />
</div>
</Router>
);
I'm trying to find the best way of handling this with React Router (seems like it would have to handled with some type of conditional maybe? - "if my current route matches any one of these routes, then render like so else render this.").
Thanks!
You have at least two possibilities:
Use Route "path" property to test the route and render the component. Path property accepts path.to.regexp expressions.
Wrap your component with withRouter method and inside Nav test if the route matches and render null otherwise.
First answer:
const App = () => (
<Router>
<div>
<Route path="/(?!signin|signup)" component={Nav}/>
<div>
<Route exact path="/" component={Home} />
<Route path="/account" component={Account} />
<Route path="/news" component={News} />
</div>
<Footer />
</div>
</Router>
);
Second answer:
import { withRouter } from 'react-router'
const NavWithRouter = withRouter(Nav);
const App = () => (
<Router>
<div>
<NavWithRouter/>
<div>
<Route exact path="/" component={Home} />
<Route path="/account" component={Account} />
<Route path="/news" component={News} />
</div>
<Footer />
</div>
</Router>
);
<Route
path={`foo/(A|B|C)`}
component={() => (<Baz {...props}/>)}
/>
Where A,B,C are the different routes like foo/A.
I usually use two different Layout pages. And within the Layout pages, have a router for the content.
My code will look like this:
<Router>
<Route path="/login" component={AuthLayout} />
<Route path="/logout" component={AuthLayout} />
<Route path="/some/path" component={Layout} />
</Router>
Within each Layout, there will be the usual header / footer / navbars and then another set of routes.
<div className="auth-layout">
<header className="auth-layout__header"></header>
<main className="auth-layout__content">
<Switch>
<Route path="/login" component={Login} />
<Route path="/logout" component={Logout} />
</Switch>
</main>
</div>
In this way, I have a direct mapping from requirements to code. In my code, there are much more differences between the two layouts.
Just use a prop for this & inside the children your are able to conditional render the nav.
<Route exact path="/" render={() => <Home hasNav={false} />}

React-routing config issue to change new home page

I am new to react-router.
In current app we are using below react-router
module.exports = (
<Router history={HashHistory}>
<Route path="/" component={Frame}>
<IndexRoute component={Page1} />
<Route path="all" component={Page2} />
<Route path="admin" component={Page3} />
<Route path="proxy" component={Page4} />
</Route>
</Router>
);
due to some changes now I want to make different page as home page but also want to make minimum changes to unimpact the current functionalities. Using the below router config but not working
<Router history={HashHistory}>
<Route path="/" component={Home}>
<Route path="achieve" component={Frame}>
<Route path ="achieve" component={Page1}>
<Route path="all" component={Page2} />
<Route path="admin" component={Page3} />
<Route path="proxy" component={Page4} />
</Route>
</Route>
</Route>
</Router>
Any pointer to resolve the issues and to explore this?
Thanks in advance.
If you wants to make each page as a home page then don't use nested route, make the separate route for each.
Try this:
<Router history={HashHistory}>
<Route path="/" component={Home}/>
<Route path="/achieve" component={Frame}/>
<Route path ="/achieve" component={Page1}/>
<Route path="/all" component={Page2} />
<Route path="/admin" component={Page3} />
<Route path="/proxy" component={Page4} />
</Router>
Use nesting in that route where you want to use some component inside that. Lets say you want to use some component inside admin page then :
<Router history={HashHistory}>
<Route path="/" component={Home}/>
<Route path="/achieve" component={Frame}/>
<Route path ="/achieve" component={Page1}/>
<Route path="/all" component={Page2} />
<Route path="/admin" component={Page3} >
<IndexRoute component={comp1}/>
<Route path="/xyz" component={comp2}/>
</Route>
<Route path="/proxy" component={Page4} />
</Router>
Follow these links for better explanation:
https://css-tricks.com/learning-react-router/
https://medium.com/#dabit3/beginner-s-guide-to-react-router-53094349669#.sjzpetwbb
Please comment if need any help.

Adding deep Links using react-router

Using the below Route configuration -
<Router history={hashHistory}>
<Route name="Home" path="/" component={BaseLayout}>
<Route name="Gateways" path="/gateways" component={DashboardLayout}>
<Route name="Login" path="/login" component={Login}/>
<Route name=":id" path="/gateways/:id">
<IndexRoute name="Dashboard" component={ViewGateWay}/>
<Route name="Access Points" path="/accesspoints" component={AccessPoints}>
<Route name=":id" path="/:id" component={ViewAccessPoint}/>
</Route>
<Route name="Devices" path="/devices" component={Devices}>
<Route name=":id" path="/:id" component={ViewDevice}/>
</Route>
</Route>
<IndexRoute component={Gateways} />
</Route>
<IndexRedirect to="Login" />
</Route>
</Router>
Using name in the Route for breadcrumbs. Have a side menu which have links to /gateways/:id, /gateways/:id/devices, /gateways/:id/accesspoints, further the last two have links to individual devices and access points using Link as /gateways/:id/devices/:id and /gateways/:id/accesspoints/:id. When I am giving the link in the side menu as
<Link to="/gateways/${this.props.params.id}/accesspoints">Access Points</Link>
OR
<Link to="/accesspoints">Access Points</Link>
I am not getting the correct page. Same goes with the devices link. I am trying to achieve the below API's along with breadcrumb.
home/gateways/GW_ID1/dashboard
home/gateways/GW_ID1/accesspoints
home/gateways/GW_ID1/accesspoints/GW_AP1
home/gateways/GW_ID1/devices
home/gateways/GW_ID1/devices/GW_DV1
What is the correct way to Link ? Not using any handler.
After a bit of brainstorming, came up with a solution what I wanted to achieve
<Route name=":gid" path="/gateways/:gid">
<Route name="Dashboard" path="/gateways/:gid/dashboard" component={ViewGateWay}/>
<Route name="Access Points" path="/gateways/:gid/accesspoints" component={AccessPoints}>
<Route name=":apid" path="/gateways/:gid/accesspoints/:apid" component={ViewAccessPoint}/>
</Route>
<Route name="Devices" path="/gateways/:gid/devices" component={Devices}>
<Route name=":did" path="/gateways/:gid/devices/:did" component={ViewDevice}/>
</Route>
</Route>