React Router

There are many way to route web calls to our web pages etc. React also comes with it’s own capability, which we can load by running

yarn add react-router-dom
yarn add @types/react-router-dom

If you’ve created your React application using yarn create react-app –typescript then go to the index.tsx and edit it to look like this

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter, Route } from 'react-router-dom'
import * as serviceWorker from './serviceWorker';
import About from './components/About';
import Home from './components/Home';

ReactDOM.render((    
    <BrowserRouter>
      <Route exact path="/home" component={Home} />
      <Route exact path="/about" component={About} />
  </BrowserRouter>), 
    document.getElementById('root'));

serviceWorker.unregister();

Now, let’s create a couple of React components which will act as our routes. Create a folder named components off of the root folder and add two files, about.tsx and home.tsx to the folder. The code for each is shown below (and the files should go in the folder src/components)

// about.tsx

import React, { Component } from 'react';

export default class About extends Component {
    render() {
        return (
            <div>About</div>
        );
    }
}

and

// home.tsx

import React, { Component } from 'react';

export default class Home extends Component {
    render() {
        return (
            <div>Home</div>
        );

    }
}

We’re not using the App.* files, so they can be deleted.

Obviously we can also add a root route, i.e.

<Route exact path="/" component={Home} />