React Router basics

Let's create our first page, ie., Home page. We create the component for the page - Home.js,

import React from 'react';

const Home = () => {
  return (
    <div>
      <h3>React Router from JS Mates</h3>
      <p>
        We will create a simple Help center app and Learn the concepts of React
        router along the way
      </p>
    </div>
  );
};

export default Home;

Then, we can render the component in App.js,

import React from 'react';
import Home from './Home';
import './styles.css';

export default function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}

This will render the application with the Home component.

But our idea is to render it like a page on the root URL (i.e., / URL). For that, we are going to use react-router-dom library.

import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './Home';
import './styles.css';

export default function App() {
  return (
    <Router>
      <Route path="/">
        <Home />
      </Route>
    </Router>
  );
}

We have used two components from react-router-dom,

  • BrowserRouter component will enclose all the routes. It helps to check the URL and load the relevant route based on the URL.
  • Route component will help to create new pages.

Here in our example, we define the home route with path - / and render the Home component when user access the URL.

<Route path="/">
  <Home />
</Route>

If you change the path props to /home, then

  • / URL won't render anything
  • /home will render the Home component

This way, you can define the URL of the route using path props.

We haven't discussed in detail BrowserRouter, we will see the different types of the router in the next lessons.

You can play with the code for this lesson here,