English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS Router

In this chapter, we will learn how to set up routing for the application.

No.1Step-Install React Router

a simple installation methodreact-C:\ Users \ username \ Desktop \ reactApp> npm install reactiniscommand prompt

Run the following code segment in the window.-C:\ Users \ username \ Desktop \ reactApp> npm install react

No.2Step-router

Create componentAppAt this step, we will create four components. TheComponents will be used as tab menu. After route changes(Home), (About),(Contact)

main.js

The rendering of other three components.
import React from 'react';-import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-dom';-router
class App extends React.Component {
   render() {
      return (
         <div>
            <ul>
            <li>Home</li>/li>
            <li>About</li>/li>
            <li>Contact</li>/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;

No.3Step-Add Router

Now, we will add the route to the application. This time, we will render, rather thanAppRender elements as in the previous exampleRouter. We will also set up 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'))

When the application starts, we will see three clickable links that can be used to change the route.