hitesh
hitesh

Reputation: 499

react router not rendering the component

I am trying to learn react route configuration. I am adding all the navigation link at one place which is entry point index.js and my expectation is when someone react to the path configured during navigation, respective component should be loaded in the briwser. I am adding all the route path in my entry file index.js as follow:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
import { BrowserRouter, Route, hashHistory } from 'react-router-dom';
import AboutUs from './AboutUs.js';
import ContactUs from './ContactUs.js';
import {Switch} from 'react-router';

ReactDOM.render(
  (<BrowserRouter>
     <Switch>
          <Route path="/" component={App}/>
          <Route path="/about-us" component={AboutUs}/>
          <Route path="/contact-us" component={ContactUs}/>
     </Switch>
   </BrowserRouter>)
, document.getElementById('app'));

app.js is as follows :

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

class App extends Component {

  constructor(props){
    super(props);

  }


  render() {
   return (
     <div>
       <h1>React Router Tutorial</h1>
       <ul role="nav">
         <li><Link to="/about-us">About</Link></li>
         <li><Link to="/contact-us">Contact</Link></li>
       </ul>
     </div>
   )
 }

}
export default App;

AboutUs.js is as follows :

import React, { Component } from 'react';

class AboutUs extends Component {

  render(){
    return(
      <div>
        AboutUs
      </div>
    );
  }
}

export default AboutUs ;

ContactUs.js is as follows :

import React, { Component } from 'react';

class ContactUs extends Component{

  render(){
    return(
      <div>
        Contact Us
      </div>
    );
  }
}

export default ContactUs;

But when I click on any of the link /about-us or /contact-us , it does not load any content and displays the same app.js as follows

enter image description here

Can someone please tell me why it is happening?

Upvotes: 6

Views: 16977

Answers (2)

Daniel Andrei
Daniel Andrei

Reputation: 2684

I belive it's matching your first Route, the App one since you haven't specified that it should be exact.

You can do this :

<Switch>
          <Route exact path="/" component={App}/> // it will match only for '/'
          <Route path="/about-us" component={AboutUs}/>
          <Route path="/contact-us" component={ContactUs}/>
</Switch>

Upvotes: 6

Agney
Agney

Reputation: 19224

Switch renders the first route that it matches in the order that it is given.

<BrowserRouter>
  <Switch>
       <Route path="/about-us" component={AboutUs}/>
       <Route path="/contact-us" component={ContactUs}/>
       <Route path="/" component={App}/>
  </Switch>
</BrowserRouter>

Because you had given '/' as first route, anything would match it and render App component.

Upvotes: 9

Related Questions