Nested Views

In the preceding examples, we implemented view navigation in the App component by using the Switch, Route, and Link components provided by React Router. We can use these routing components inside of any other component so that we can build nested views and nested routes.

Let's try to illustrate this with an example. Suppose that we want to add a list of winemakers to our application. We can add a new item to the navigation bar that allows us to navigate to a page showing that list.

The following screenshot shows how the new layout will appear:

So, let's change the App component's JSX markup, as follows:

import React, { Component } from 'react';
import './App.css';
import Catalog from './Catalog';
import About from './About';
import WineMakers from './WineMakers';
import { Switch, Route, Link } from 'react-router-dom';

class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">The Catalog App</h1>
<nav>
<ul>
<li><Link to='/'>Catalog</Link></li>
<li><Link to='/winemakers'>WineMakers</Link></li>
<li><Link to='/about'>About</Link></li>
</ul>
</nav>
</header>
<Switch>
<Route exact path='/' component={Catalog}/>
<Route path='/winemakers' component={WineMakers}/>
<Route path='/about' component={About}/>
</Switch>
</div>
);
}
}

export default App;

We imported the WineMakers component, defined a route that maps the /winemakers path to the new component, and added a link to navigate to it.

We can implement the list of winemakers as follows:

import React from 'react';
import WineMaker from './WineMaker';
import { Switch, Route, Link } from 'react-router-dom';

class WineMakers extends React.Component {
renderWineMakersList() {
return <ul>
...
<Link to="/winemakers/WM2">Wine & Co</Link>
</li>
</ul>;
}

render() {
return <Switch>
...

export default WineMakers;

The WineMakers component has the renderWineMakersList() method that returns the React element implementing a list of links to each winemaker. This method is used as the value of the render attribute of the route matching the /winemakers path in the render() method of the component. The other routes get the path pointing to each specific winemaker and render the WineMaker component according to the identifier code.

You may notice that we are implementing a view in the WineMakers component that is shown inside of the view implemented in the App component. In other words, we implement nested views by composing components that implement views.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.164.228