0
votes
import React, { Component } from 'react';
import {BrowserRouter as Router,Route,Switch} from 'react-router-dom';
import Home from './home/components/home'

class App extends Component {
render() {
return (
  <div className="App">

      <Router>
        <Switch>
        <Route  path="/home" component={Home}>
        </Route><!--working-->

        <!--<Route  path="/" component={Home}>
        </Route> not working -->

        </Switch>
      </Router>

  </div>
);
 }
}     


class Home extends Component{    
   render = () => {

    return (
        <div>
            <div>Home</div>
            <Route exact path={`${this.props.match.url}/signin`}   component={SignIn}>
            </Route>
        </div>

    );
 }
}

I have the following piece of code. In the App component I want to create nested routes. '/' being the root route and /signin being the nested route. However /signin doesnt render the SignIn component, just the 'Home' div. When I replace '/' with '/home' in App component then '/home/signin' renders the 'Home' div and 'SignIn' component. What am I doing wrong here?

1

1 Answers

1
votes

Nested routes don't work on the root. Simply use a layout component that acts as a parent component to achieve the same results. Once you click a link, the child component will be rendered within the designated area in the layout component. I've created an example for you on CodePen: https://codepen.io/anon/pen/EXMJzG

const {
  BrowserRouter, 
  Link, 
  Route
} = ReactRouterDOM;
const Router = BrowserRouter;

// App
class App extends React.Component{
  render(){
    return(
    <Router>
      <div className="container">
        <Layout>
          <Route exact path="/" component={Home} /> 
          <Route exact path="/signin" component={SignIn} /> 
          <Route exact path="/cake" component={Cake} /> 
        </Layout>
      </div>
    </Router>
    )
  }
}

//Layout
const Layout = ({children}) => (
  <div>
    <header>
      <h1>Header</h1>
    </header>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/signin">Sign In</Link>
      <Link to="/cake">Cake</Link>
    </nav>
    <section>
      {children}
    </section>
    <footer>
      <p>Footer</p>
    </footer>
  </div>
)

//Home
const Home = ()=>(
  <div>
    <h1>Hello World</h1>
  </div>
)

//SignIn
const SignIn = ()=>(
  <div>
    <h1>Sign In</h1>
  </div>
)

//Cake
const Cake = ()=>(
  <div>
    <h1>Free Cake</h1>
  </div>
)

ReactDOM.render(<App />,document.getElementById('app'));