Joined a new team, and found below snippet:
const bookListContainer = (location, cb) => {
require.ensure([], require => {
cb(null, require('somepath').default)
}, 'bookList')
}
<Route path="/" component={App}>
<Route path="home" component={HomeComponent} />
<Route path="bookList/:bookId" getComponent={bookListContainer} />
</Route>
what is the difference between component and getComponent? And for bookListContainer, what does it exact do? cannot understand require.ensure()
thanks
I recommend you to read code splitting: https://webpack.github.io/docs/code-splitting.html
You will learn some important concepts there to understand this code.
Regards!
This is a way to asynchronously load routes by splitting them into separate bundles.
getComponent will fire when the route is matched and consequently require what is necessary for that bundle bookList
This is a way to assist reducing the initial load time of your application.
Related
I have some React routes that when I nest one route inside another, I need to repeat the route path.
To explain, for example:
<Route
path="admin">
<Switch>
<Route
path="admin/specific/:id"
component={SpecificAdmin} />
<Route
exact
path="admin"
component={AdminPage}>
</Route>
<Route
exact
path="admin/edit/new"
component={EditSpecificAdmin} />
</Switch>
</Route>
I want a page where I can see the list of items, one for adding a new one and another for looking, editing a specific item. So I thought about the paths edit/new and specific/1.
So the routes do not detect when I write specific/1 (the specific id) and not either the admin nesting, so I need to write the admin in each one...
As Tareq aziz said, you can easily have intel in props.
You can create another router to pass easily new value:
// your original component
import AdminRouter from './Admin/Router';
export default () => {
return (
<Route path="admin">
<AdminRouter />
</Route>
);
}
// in ./Admin/Router.js
export default (props) => {
return (
<Switch>
<Route
exact
path={`${props.match.path}/specific/:id`}
component={SpecificAdmin}
/>
<Route
exact
path={`${props.match.path}`}
component={AdminPage}
/>
<Route
exact
path={`${props.match.path}/edit/new`}
component={EditSpecificAdmin}
/>
</Switch>
);
}
I'm not sure though if the order of the routes are correct.
I think you can get your current page's url from props using location.pathname or match.url. You can see my image. Then you may add your nested route after that. Hope it will help you
You may code your path like this way
path=`${this.props.location.pathname}/edit/new`
path=`${this.props.location.pathname}/specific/:id`
I'm reading about static vs dynamic routing in React Router, and I'm struggling to identify the advantages of the latter (and why v4 chose to go with it). I can see the advantage of listing out all the routes for an application (static), as well as the component that each route maps to, allowing you to trace what would be rendered given a specific URL. But I'm not seeing any clear advantage to dynamic routes.
If anything, I can only see disadvantages, because there is no clear way to see what state a URL will map to, without starting at the root app element and working your way through the routes (though I might be mistaken).
What situations does dynamic routing address? Why is it preferable to static routing (maybe specifically in React apps)?
Dynamic Routing
From the react router docs:
When we say dynamic routing, we mean routing that takes place as your
app is rendering, not in a configuration or convention outside of a
running app.
Think of routes as components
The earlier versions of react-router (pre v4) used to have static routes. This led
to a centralized routing in apps like:
<Router>
<Route path='/' component={Main}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route onEnter={verifyUser} path='profile' component={Profile} />
...
</Route>
</Router>
However, this is not exactly the React way of doing things. React focuses on composition using components based logic. So, instead of imagining our Routes as a static system, we can imagine them as components, which is what react-router v4 brings in and the primary philosophy behind it.
Therefore, we can use Route as we would use any React component. This lets us add Route components as and when we build different components. One advantage of doing this is we can decouple the routing logic to the components needing them.
Nesting routes
The About component can handle all the routes and conditionally render parts of UI based on the url (say /about/job or /about/life etc).
Another thing to note is that a Route component will either render the component for a matching route or null. Example, the following Route renders the About component for a route /about and null (or nothing) otherwise.
<Route path='about' component={About} />
This is also similar to how we're used to conditionally rendering components in React:
route === '/about' ? <About /> : null
Now if we need to render some other components inside the About component for routes /about/job or /about/life we can do it like:
const About = ({ match ) => (
<div>
...
<Route path={`${match.url}/job`} component={Job} />
<Route path={`${match.url}/life`} component={Life} />
</div>
)
Dynamic imports and code splitting
Personally, I've also found this approach works better for me in case I'm using dynamic imports with code-splitting, since I can add dynamic routes in any of my components. For example,
import Loadable from 'react-loadable';
const Loading = () => (
<div />
);
const Job = Loadable({
loader: () => import('./Job'),
loading: Loading,
});
const Life = Loadable({
loader: () => import('./Life'),
loading: Loading,
});
...
render() {
return (
...
<Route path={`${match.url}/job`} component={Job} />
<Route path={`${match.url}/life`} component={Life} />
)
}
Responsive routes
Another great use case for dynamic routing is creating responsive routes which is explained beautifully in the react router docs and a recommended read. Here's the example from the docs:
const App = () => (
<AppLayout>
<Route path="/invoices" component={Invoices}/>
</AppLayout>
)
const Invoices = () => (
<Layout>
{/* always show the nav */}
<InvoicesNav/>
<Media query={PRETTY_SMALL}>
{screenIsSmall => screenIsSmall
// small screen has no redirect
? <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
</Switch>
// large screen does!
: <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
<Redirect from="/invoices" to="/invoices/dashboard"/>
</Switch>
}
</Media>
</Layout>
)
Summarizing the docs, you'll notice how simple and declarative it becomes to add the Redirect to large screen sizes using dynamic routing. Using static routing in such cases would be quite cumbersome and would need us to put all the routes in a single place. Having dynamic routing simplifies this problem since now the logic becomes composable (like components).
Static Routing
There are some problems which are not solved easily with dynamic routing. An advantage of static routing is that it allows for inspection and matching of routes before rendering. Hence it proves useful especially on server side. The react router team is also working on a solution called react-router-config, quoting from which:
With the introduction of React Router v4, there is no longer a
centralized route configuration. There are some use-cases where it is
valuable to know about all the app's potential routes such as:
Loading data on the server or in the lifecycle before rendering the next screen
Linking to routes by name
Static analysis
Hope this provides a good summary of both Dynamic Routing and Static Routing and the use cases for them :)
According to the React-Router docs:
When we say dynamic routing, we mean routing that takes place as your
app is rendering, not in a configuration or convention outside of a
running app. That means almost everything is a component in React
Router.
Its clear for the explanation that, all you Routes are not initialised at the start of your application,
In React-router v3 or below, it used static Routes and all Routes would be initialised at the top level, and nesting used to be achieved like
<Router>
<Route path='/' component={App}>
<IndexRoute component={Dashboard} />
<Route path='users' component={Users}>
<IndexRoute component={Home}/>
<Route path="users/:id" component={User}/>
</Route>
</Route>
</Router>
With this API setup, react-router was reimplementing parts of React (lifecycles, and more), and it just didn’t match the composition logic that React recommends on using.
With Dynamic Routes the following advatages, comes to be foreseen
Nested Routes
Nested Routes with Dynamic Routing are more like
const App = () => (
<BrowserRouter>
{/* here's a div */}
<div>
{/* here's a Route */}
<Route path="/todos" component={Todos}/>
</div>
</BrowserRouter>
)
// when the url matches `/todos` this component renders
const Todos = ({ match }) => (
// here's a nested div
<div>
{/* here's a nested Route,
match.url helps us make a relative path */}
<Route
path={`${match.path}/:id`}
component={Todo}
/>
</div>
)
In the above example, only when /todos matches the route-path, the Todo component is mounted and only then the Route path /todos/:id is defined.
Responsive routes
The React-router docs have a good use case for this.
Consider a user navigates to /invoices. Your app is adaptive to different screen sizes, they have a narrow viewport, and so you only show them the list of invoices and a link to the invoice dashboard. They can navigate deeper from there.
However on a large screen, navigation is on the left and the dashboard or specific invoices show up on the right.
and hence /invoices is not a valid Route for a large screen and we would want to redirect to /invoices/dashboard. This may so happen, the user rotates his/her phone from a portait to a landscape mode. This can easily be done using dynamic Routing
const Invoices = () => (
<Layout>
{/* always show the nav */}
<InvoicesNav/>
<Media query={PRETTY_SMALL}>
{screenIsSmall => screenIsSmall
// small screen has no redirect
? <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
</Switch>
// large screen does!
: <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
<Redirect from="/invoices" to="/invoices/dashboard"/>
</Switch>
}
</Media>
</Layout>
)
Using Dynamic Routes with React Router’s, think about components, not static routes.
Code Splitting
One great feature of the web is that we don’t have to make our visitors download the entire app before they can use it. You can think of code splitting as incrementally downloading the app. This is made possible with Dynamic Routing.
The advantages it brings is that all your code need not be downloaded at once and hence it makes initial rendering faster.
Here is a good article that helps you setUp codeSplitting for your application
Writing Composable Authenticated Routes
With Dynamic Routing its also made easier to write PrivateRoutes(an HOC that does authentication) which allow for authenticating users and providing them access to specific Routes and redirecting otherwise. This call all me made very generically
A Typical Private Route would be look like
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
and can be used as
<PrivateRoute path="/protected" component={Protected} />
I know this question has been asked quite a few times and I've looked at the answers, but I haven't gone very far. I'm creating a few boilerplates (because I am tired of writing the same base code over and over again) but I can't get past RR v4; specifically, params.
This boilerplate is pretty simple. Right now, I am navigating to posts with RR4, however, even if I route to a post with a different slug, it always returns the same post. (first-post). Any advice on how to navigate properly? I think the docs are not too great where params are concerned. Here's the repo:
https://github.com/boilerstrapper/react-boilerstrap
UPDATE:
Here's some code:
components/App/index.js
// ...imports
export const App = () => {
return (
<div>
<Nav />
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/posts' component={PostList} />
<Route exact path='/posts/:slug' component={PostListItem} />
<Route exact path='/products' component={ProductList} />
<Route exact path='/products/:slug' component={ProductListItem} />
<Route exact path='/login' component={Login} />
<Route component={NotFound} />
</Switch>
</div>
);
}
So when you just change the param :slug in the url, you only changed whats been passed as a prop (props.match.params.slug) into the container component you have, but that doesn't destroy the existing component rendered and reconstruct it (since its the same one). This means the constructor isn't called again where you make your http request for the data.
To fix this, I've done similar to the following:
componentWillMount() {
this.loadEvents();
}
componentWillReceiveProps(nprops) {
this.loadEvents(nprops.match.params.orgId);
}
loadEvents(orgId = this.props.match.params.orgId) {
axios.get(`/_api/org/events?org=${orgId}`)
.then(res => {
this.setState({ events: res.data });
})
.catch(alert);
}
So that it requests the data when the parameters change!
So, I actually found the answer. I wrote this in my API:
const slug: string = req.body.slug
Instead of:
const slug: string = req.params.slug
I know how simple Router works like this:
<Router history={hashHistory}>
<Route path='/' component={Home} />
<Route path='/address' component={Address} />
</Router>
But I came along this type of routing, which I am not able to understand. Can somebody please explain how the following is working? Or please edit my question as more suitable to these type of routes.
I can only understand path in every Route that if I type this on browser then this Route will be triggered. But I am not able to understand what its running, what components and other things. Please tell me what this type of routing is called and more info on this.
File: routes.js
import React from 'react';
import { Router, Route } from 'react-router';
import App from './app';
export default (
<Router>
<Route name="root" component={App}>
<Route name="home" path="/" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('./components/routes/home').default);
});
}}
/>
<Route name="homeSeries" path="/series/:series_id" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('./components/routes/home').default);
});
}}
/>
<Route name="homeStatus" path="/status/:status" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('./components/routes/home').default);
});
}}
/>
...
...
Lots of more Route
...
...
</Route>
</Router>
);
This routing also works same as the routing you described above. So for example
<Route name="home" path="/" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('./components/routes/home').default);
});
}}
/>
The above code will load './components/routes/home' component on "/" route.
Actually this kind of routing is usually used for code splitting (e.g. in webpack module bundler).
Usually webpack bundle the all files into a single bundle file. So in your first code
<Router history={hashHistory}>
<Route path='/' component={Home} />
<Route path='/address' component={Address} />
webpack will bundle 'home' and 'address' components into a single module.
But if you use require.ensure like the second code snippet, webpack will divide the module into multiple modules (called chunks) at each require.ensure.
This is useful because user will only download the required module at initial time. So for example if user goes to /address, then only address chunk will be downloaded at first and not home component (which can be downloaded asynchronously later).
That example is using require.ensure to asynchronously load components. This is most likely being done to allow for code splitting (eg. with Webpack). Code splitting allows you to split your bundle across multiple files, decreasing the amount of code that has to be sent on initial load and only requesting extra code when it is necessary. You can read more about code splitting in the Webpack documentation.
The <Route>s are using the getComponent prop, which is React Router's way for allowing asynchronously loaded components. getComponent expects a function which takes a location and a callback function. The asynchronously loaded component is passed to the <Route> using the callback function. Once the callback has been called, the loaded component will be rendered.
I am currently using React Router and have routes that use the browserHistory, for example:
import { Router, Route, IndexRedirect, browserHistory } from 'react-router';
<Router history={browserHistory}>
<Route path="tasks" component={Tasks}>
<IndexRoute component={List} />
<Route path="/:id" component={Item} />
</Route>
</Router>
Which allows me to do routes such as:
/tasks/
/tasks/1234
This works, but we have come across a situation where we have two views that are displayed at the same time. We'd like for the link to be shareable and have the app open with both views.
So for example, if we have tasks on the left side of the screen, and a shop on the right, we'd like for there to be two independent parts of the path, something like:
/tasks/1234/#/shop/item/xyz
The shop route should be independent of the left of the hash, and the tasks route should be independent of the right of the hash, so that /new-feature/xyz/#/shop/item/xyz should still render the same view on the right side of the window.
Is it possible to have React Router do routes like this? Or will I have to write a custom router to solve this?
I'm guessing I'd basically have to combine the browserHistory and hashHistory together, but I don't think that's possible with React Router out of the box.
I think rolling your own router just to handle this case might be a little overboard. You can have as many different paths in your route config as you want, and access param information in your components:
<Router history={browserHistory}>
<Route path="/" component={App} />
<Route path="/tasks/:taskId" component={App} />
<Route path="/shop/:shopId" component={App} />
<Route path="/tasks/:taskId/shop/:shopId" component={App} />
</Router>
let App = ({ params }) => // simplified
<div>
{ params.shopId && <Shop /> }
{ params.taskId && <List /> }
</div>
Just a thought.. I think there are several ways to augment this to handle more complex scenarios but this would definitely work for what you've specified in the question (for the most part).
Update: Above is 'hardcoded', but of course you do not need to write out every combination by hand. This is what loops are for.
import * as routeComponents from './routeComponents'
<Router history={browserHistory}>
{ routeComponents.map(r => <Route {...r} />) }
</Router>
let App = ({ params }) =>
<div>
{ routeComponents.reduce((matches, r) => ([
...components,
...(params[r.slug] ? [r.component] : [])
]), [])}
</div>
We have developed our own router Boring Router with "parallel routing" support, though it depends on MobX and works differently with React Router in many ways.
In Boring Router, a parallel route is stored as query string parameter prefixed with _. E.g., /app/workbench?_sidebar=/achievements.
Check out a complete example here.