Andrew Jensen
Andrew Jensen

Reputation: 167

React Router v4 - Nesting Routes Issue

I have the following App component.

class App extends React.Component {
  constructor() {
    super();
    this.state = {}
  }

  // various methods that interact with state defined here

  render() {
    const Main = () => (
      <div className="main-wrapper">
        <ListPicker/>
        <ListPane/>
      </div>
    );

    const Search = () => (
      <div className="search-wrapper">
        <ul className="search-results">
          <li>Search Results</li>
        </ul>
      </div>
    );

    return (
        <div className="app-wrapper">
          <Title/>
          <SearchBar listResults={this.listResults}/>

          <Route exact path="/" component={Main}/>
          <Route path="/search" component={Search}/>
        </div>
    )
  }
}

Which is rendered in index.js:

import React from 'react';
import { render } from 'react-dom';
import { 
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

import App from './components/App';

const Root = () => {
  return (
    <Router>
      <div>
        <Route exact path="/" component={App}/>
      </div>
    </Router>
  )
};

render(<Root/>, document.getElementById('root'));

Towards the bottom of App you can see I'm trying to have either the Main component or Search component render below <Title/> and <SearchBar/> based on the paths / or /search. As far as I can tell from the React-Router docs, I'm doing what's shown in their example app, but I can't get this to work correctly. With this current setup Main renders fine at / but when navigating to /search nothing renders inside of <Root/>. I also tried wrapping those two <Routes/> in a <Switch/> but got the same result. Am I missing something?

Upvotes: 0

Views: 127

Answers (1)

You put a exact Route in you index.js. So the route /search can't find a way. So change to:

const Root = () => {
  return (
    <Router>
      <div>
        <Route path="/" component={App}/>
      </div>
    </Router>
  )
};

Upvotes: 1

Related Questions