reactjsreact-routerreact-routing

react router not getting route after click


My routes.js is something like:

const routes =  (
  <Route path="/" component={App}>
        <Route path="/login" component={Login} />
        <Route path="/one" component={One} />
        <Route path="/two" component={Two} />
  </Route>
)
export default routes

I have a header file in App component and my header file looks like:

class Header extends Component {
  render() {
    return (
      <div>
        <h3><Link to={`/one`}>One</Link></h3>
        <h3><Link to={`/two`}>Two</Link></h3>
      </div>
    )
  }
}

export default Header

When I run localhost:3333 it goes to the App page that containse Header with One and Two. But when I click on that, it is not displaying the content or component of One and Two.

What am I missing in the router?

Need help.


Solution

  • Let me guess you missed this.props.children. So your component should look like

    class Header extends Component {
      render() {
        return (
          <div>
            <h3><Link to={`/one`}>One</Link></h3>
            <h3><Link to={`/two`}>Two</Link></h3>
            <div>{this.props.children}</div> // this is the way how React renders different components based on route 
          </div>
        )
      }
    }
    
    export default Header
    

    React-Route link for more information. I hope it will help you.

    Thanks