Reputation: 167
I know this question's already been answered, and I read the React Router docs regarding nested routes, but I still can't see how to make it work with my current React app. All the examples given for nesting routes with v4 are with functional components. But what if I have a class component and need to nest a route? For example, my main app component is at /
and I want to add a route for a search page at /search
and I need that route to be a nested route(child route?) because the search page needs to read from state and state is only accessed from the app component. So I tried the following (note the <Route/>
at the bottom):
//App.js
class App extends React.Component {
constructor() {
super();
this.state = {}
}
// various methods that interact with state defined here
render() {
return (
<div className="app-wrapper">
<Title/>
<SearchBar/>
<ListPicker/>
<ListPane/>
<Route path="/search" component={Search}/>
</div>
)
}
}
Here's Search.js
:
class Search extends React.Component {
render() {
return (
<div className="search-wrapper">
<SearchBar/>
<ul className="search-results">
/* Read state to populate list */
</ul>
</div>
)
}
}
And I define the route to App
in index.js
:
const Root = () => {
return (
<BrowserRouter>
<div>
<Route exact path="/" component={App}/>
</div>
</BrowserRouter>
)
};
render(<Root/>, document.getElementById('root'));
With this setup nothing gets rendered when navigating to /search
. Not sure what to do given the disparity between my setup and the examples I've found online.
Upvotes: 1
Views: 847
Reputation: 281686
Nothing gets rendered because you specify and exact match for path /
and hence /search
is not matched, just remove the exact
prop from the route
You need to use it like
const Root = () => {
return (
<BrowserRouter>
<div>
<Route path="/" component={App}/>
</div>
</BrowserRouter>
)
};
render(<Root/>, document.getElementById('root'));
Upvotes: 1
Reputation: 300
You need to use render for nested Routes in React-Router v4. Something like this.
<Router history={history}>
<Route path="/" render={() => (
<div>
<Route path="/" component={HomeView} />
<Route exact path="/search" component={Search}/>
</div>
)}/>
</Router>
Upvotes: 0