Using React router in your react application

React router allows you to use multiple pages in your web app.  Usually in react, the react-router doesn't refreshes the page instead just changes the page.

Step 1:

Install react router:

npm i --save react-router-dom

Step 2:

Navigate to the index.js folder and import the required components:

import { Route, Routes, BrowserRouterfrom 'react-router-dom';

Step 3:

Add this routing function in index.js

const Routing = () => {
  return (
    <BrowserRouter basename={process.env.PUBLIC_URL}>
      <Routes>
          <Route path="/" element={<App/>} />
          <Route path="/project" element={<Project/>} />
          <Route path="/contact" element={<Contact/>} />
     </Routes>
    </BrowserRouter>
  );
}

Instead of rendering App component render the Routing component as below in index.js:

ReactDOM.render(
  <React.StrictMode>
    <Routing />
  </React.StrictMode>,
  document.getElementById('root')
);

Voila! Now router as been added to your react project.

When you visit localhost:3000 the App component will be rendered,

if you visit localhost:3000/project the Project component will be rendered,

if you visit localhost:3000/contact then the Contact component will be rendered.

Additional steps:

Now these routes are set to their own components to be rendered.  Now you can use Link in any file inside your project as follows:

import { Link } from 'react-router-dom';

function App() {
  return (
    <>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
        <Link to="/project">Project</Link>
        </li>
        <li>
        <Link to="/contact">Contact</Link>
        </li>
      </ul>
    </ >
  );
}

export default App;

The above code can be placed in your App.js or any file that needs a header or navigator to navigate to different components (or) pages.  

Note: If you use <a> instead of <Link> then the page will be refreshed which was deprecated in react.

Source code for a complete router app is available at https://bitbucket.org/balayokesh/router-tutorial/src/master/

If you are looking for some keywords of advanced concepts of react-router. There are also useParams, userRouteMatch, useLocation, useHistory, Redirect which can be used for some advanced routing.

Happy coding :)

Comments