HI WELCOME TO SIRIS

Router - reactjs

What is Router in ReactJS?

  • Routing being a key aspect of web applications (and even other platforms) could not be left out in React.
  • You can make full fleshed single page applications with React if we harness the powers of routing. This does not have to be a manual process, we can make use of React-Router.
 learn reactjs tutorial - reactjs router - reactjs example
learn reactjs tutorial -
reactjs router
- reactjs example - react tutorial - reactjs - react

Step1: Install React Router

  • Simple way to install react-router is to run the following code snippet in command prompt window.
C:\Users\username\Desktop\reactApp>npm install react-router
click below button to copy the code. By reactjs tutorial team
Article tag : react , react native , react js tutorial , create react app , react tutorial , learn react

Step2: Create Components

  • In this step, we are creating four components. The App component will be used as a tab menu.
  • The other three components (Home), (About) and (Contact) are rendered once the route has changed.

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
   render() {
      return (
         <div>
            <ul>
               <li>Home</li>
               <li>About</li>
               <li>Contact</li>
            </ul>
    
           {this.props.children}
         </div>
      )
   }
}

export default App;

class Home extends React.Component {
   render() {
      return (
         <div>
            <h1>Home...</h1>
         </div>
      )
   }
}

export default Home;

class About extends React.Component {
   render() {
      return (
         <div>
            <h1>About...</h1>
         </div>
      )
   }
}

export default About;

class Contact extends React.Component {
   render() {
      return (
         <div>
            <h1>Contact...</h1>
         </div>
      )
   }
}

export default Contact;
click below button to copy the code. By reactjs tutorial team

Step 3 - Add Router

  • Now we want to add routes to our app.
  • Instead of rendering App element like in previous examples, this time the Router will be rendered.
  • We will also set components for each route.

main.js

ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
 
), document.getElementById('app'))
click below button to copy the code. By reactjs tutorial team

Output

  • When the app is started, we will see three clickable links that can be used to change the route.
 learn reactjs tutorial - reactjs router - reactjs example