mydomain
No ADS
No ADS

Undertanding ReactJS Router with a basic example (NodeJS)

  1. What is React Router?
  2. Create a project and install library
  3. Write code

1. What is React Router?

No ADS
React Router means a standard routing library in the React. It makes the application interface synchronous with the URL on the browser. The React Router allows you to route "data flow" in your application clearly. It is equivalent to assertion. If you have this URL, it shall be equivalent to this Route and the interface shall be like the following.
The idea of the router is really helpful because you are working with React, a Javascript library for programming single page applications. To develop a React application, you have to write a lot of components but need only one file to serve users. That is index.html .
The React Router helps you define dynamic URLs and select a suitable Component to render on the user browser corresponding to each URL.
<BrowserRouter> vs <HashRouter>
The React Router provides you with the 2 components such as <BrowserRouter> & <HashRouter>. These two components are different in URL type to be created and synchronized by them.
// <BrowserRouter>
http://example.com/about

// <HashRouter>
http://example.com/#/about
<BrowserRouter> is used more commonly, it uses the History API included in HTML5 to monitor your router's history while <HashRouter> uses the hash of the URL (window.location.hash) to remember everything. If you intend to support old browsers, you should be sealed to the <HashRouter>, or you want to create a React application using the client-side router, <HashRouter> is a reasonable choice.
<Route>
The <Route> component defines a mapping between an URL and a Component. That means when the user visits by an URL on browser, a corresponding Component shall be renderred on interface.
<BrowserRouter>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/topics" component={Topics}/>
</BrowserRouter>


<HashRouter>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/topics" component={Topics}/>
</HashRouter>
The exact attribute is used in the<Route> to say that this <Route> only operates if the URL on the browser is matches absolutely the value of its path attribute.

<BrowserRouter>
...
<Route path="/about" component={About}/>
...
</BrowserRouter>


http://example.com/about ==> OK Work!
http://example.com/about#somthing ==> OK Work!
http://example.com/about/something ==> OK Work!
http://example.com/about/a/b ==> OK Work!

-------------------

http://example.com/something/about ==> Not Work!
http://example.com/something/about#something ==> Not Work!
http://example.com/something/about/something ==> Not Work!

<HashRouter>
...
<Route path="/about" component={About}/>
...
</HashRouter>


http://example.com#/about ==> OK Work!
http://example.com#/about/somthing ==> OK Work!

----------------

http://example.com/something ==> Not Work!
http://example.com/something#/about ==> Not Work!

<BrowserRouter>
...
<Route exact path="/about" component={About}/>
...
</BrowserRouter>



http://example.com/about ==> OK Work!
http://example.com/about#somthing ==> OK Work!

-------------

http://example.com/about/something ==> Not Work!
http://example.com/about/a/b ==> Not Work!

http://example.com/something/about ==> Not Work!
http://example.com/something/about#something ==> Not Work!
http://example.com/something/about/something ==> Not Work!

<HashRouter>
...
<Route exact path="/about" component={About}/>
...
</HashRouter>


http://example.com#/about ==> OK Work!

----------------

http://example.com#/about/somthing ==> Not Work!
http://example.com/something ==> Not Work!
http://example.com/something#/about ==> Not Work!

2. Create a project and install library

No ADS
First of all, you needs to install the create-react-app tool and create a React project with the name of react-router-basic-app:
# Install tool:

npm install -g create-react-app

# Create project named 'react-router-basic-app':

create-react-app react-router-basic-app
Your project is created:
Next, CD to the project just created and perform the following command to install the react-router-dom library in your project:
# CD to your project

cd react-router-basic-app

# Install react-router-dom library:

npm install --save react-router-dom
Open your project on an editor which you are familiar to (For example, Atom). Open the package.json file, you shall see that the react-router-dom library has been added to your project.
Start your application:
# Start App

npm start

3. Write code

No ADS
Delete all the contents of the two files: App.css & App.js. We will write code for these 2 files.
App.css
.main-route-place {
  border: 1px solid  #bb8fce;
  margin:3px;
  padding: 5px;
}

.secondary-route-place {
  border: 1px solid #a2d9ce;
  margin: 5px;
  padding: 5px;
}
App.js
import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";

import './App.css';

class App extends React.Component {

  render()  {
    return  (
      <BrowserRouter>
        <div>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/topics">Topics</Link>
            </li>
          </ul>

          <hr />
          <div className="main-route-place">
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
            <Route path="/topics" component={Topics} />
          </div>
        </div>
      </BrowserRouter>
    );
  }

}

class Home extends React.Component {

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

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

class Topics extends React.Component {
  render( ) {
    return (
      <div>
        <h2>Topics</h2>
        <ul>
          <li>
            <Link to={`${this.props.match.url}/rendering`}>
              Rendering with React
            </Link>
          </li>
          <li>
            <Link to={`${this.props.match.url}/components`}>Components</Link>
          </li>
          <li>
            <Link to={`${this.props.match.url}/props-v-state`}>
              Props v. State
            </Link>
          </li>
        </ul>

        <div className="secondary-route-place">
          <Route
            path={`${this.props.match.url}/:topicId`}
            component={Topic} />
          <Route
            exact
            path={this.props.match.url}
            render={() =>
              <h3>
                Please select a topic.
              </h3>
            }
            />
        </div>
      </div>
    );
  }
}

class Topic extends React.Component {
  render()  {
    return (
      <div>
        <h3>
          {this.props.match.params.topicId}
        </h3>
      </div>
    );
  }
}

export default App;
It is not neccessary to change the two files: index.js & index.html:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
 
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
   
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    
  </body>
</html>
Run your application and see the results on the browser:
No ADS
No ADS