4 years ago
Zaid Bin Khalid
2,940 Views
4
In this session, we will learn how to set up a React JS router with examples and code.
Step 1 – Install a React Router
In the first step, we run the following code in the command prompt window. This is a simple way to install the react-router in the React JS.
C:\Users\username\Desktop\reactApp>npm install react-router
Step 2 – Create Components
In the second step, we create four components. The app component , home component , about the component, and contact component. As a tab menu, the App component will be used. The other three components (Home), (About), and (Contact) are rendered once the route has changed.
//main.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;
Step 3 – Add a Router
In the third step, now we add routes to the app. Instead of rendering App element, this time the Router will be rendered in React JS. 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'))
Once the steps are completed and the app is started, We will see three clickable links that can be used to change the route.
4 years ago
Zaid Bin Khalid
2,940 Views
4