React Router: How to Setup Routing in React.js

1
163
React Router Tutorial Example From Scratch

React.js is quite a famous library among JavaScript developers. Routing to front-end applications is a fundamental concept, and today I will show you how to use react-router v4 in our React.js application.

We will see Declarative React Routing for the React.js app. It is just an essential quick start of the react-router example.

React Webpack setup

We are using a Webpack with React.js to set up the environment. Webpack is the module bundler for JavaScript applications.

Step 1: Make a package.json file.

Make one project folder inside one file called package.json and copy the following code. lnstall all the react.js project’s required dependencies.

Step 2: Configure the webpack.config.js file.

Create one folder inside the root directory called app and make one file called main.js.

The further step, make one file inside the root called webpack.config.js and copy the following code into it.

// webpack.config.js

module.exports = {
    entry: './app/main.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        port: 3000
    }
};

So, we have configured the webpack, and now in the root, create one more file called index.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Router Tutorial</title>
</head>
<body>
    <div id="app"></div>
    <script type="text/javascript" src="bundle.js"></script>
</body>
</html>

Here, I have included the bundle.js file in the index.html, which is the final output file of our application.

Configure the .babelrc file in the root of the project. And put the following code into it.

{
  "presets": ["es2015", "react", "stage-3"]
}

Step 3: Build a React.js component.

In the app directory, create one component file called App.js and put the following code into it.

// App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
        <div>
          <h2>Welcome to React Router Tutorial</h2>
        </div>
    );
  }
}

export default App;

Now, in the main.js file, put the following into it.

// main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('app'));

The next step would be to type in the terminal the following command.

npm start

In the browser, go to this URL: http://localhost:3000/

Welcome to React Router Tutorial is displaying on the screen.

React Router Example

Step 4: Install the React Router module.

Type the following command in your terminal.

npm install --save-dev react-router-dom

The Router

There are two types of router objects.

  1. <BrowserRouter>
  2. <HashRouter>

If we want to handle the dynamic re,q, then use BrowserRouter and if we’re going to serve the static request, then use HashRouter.

History

Every router creates a history object to keep track of the current location of the page.

Rendering a <Router>

If we take the above example, then it will look like this.

// main.js

import { BrowserRouter } from 'react-router-dom'
import App from './App';

ReactDOM.render((
  <BrowserRouter>
    <App />
  </BrowserRouter>
), document.getElementById('root'))

This is how we can render the BrowserRouter object.

Step 5: Make two components.

First, make the Home.js component.

// Home.js

import React, { Component } from 'react';

class Home extends Component {
  render() {
    return (
        <div>
          <h2>Home</h2>
        </div>
    );
  }
}

export default Home;

Now, make another component called Dashboard.js inside the app directory.

// Dashboard.js

import React, { Component } from 'react';

class Dashboard extends Component {
  render() {
    return (
        <div>
          <h2>Dashboard</h2>
        </div>
    );
  }
}

export default Dashboard;

The next step will be to modify the App.js file.

// App.js

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

class App extends Component {
  render() {
    return (
    <Router>
        <div>
          <h2>Welcome to React Router Tutorial</h2>
          <ul>
            <li><Link to={'/'}>Home</Link></li>
            <li><Link to={'/dashboard'}>Dashboard</Link></li>
          </ul>
          <hr />
          <Switch>
              <Route exact path='/' component={Home} />
              <Route path='/dashboard' component={Dashboard} />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

The final main.js file will look like this.

// main.js

import React from 'react';
import { render } from 'react-dom';
import App from './App';

render(
  <App />, document.getElementById('app'));

Go to the URL: http://localhost:3000.

That’s it.

Fork Me On GitHub

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.