BeginnerCoder
intermediate#react#react-router#client-side-routing

Creating a React App with React Router

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to create a React app that uses React Router for client-side routing.

Introduction

To get started with this tutorial, you'll need to have Node.js and npm installed on your computer.

Step 1: Create a new React app

Create a new React app using create-react-app by running the following command in your terminal:

npx create-react-app react-router-app

Step 2: Install React Router

Install React Router by running the following command in your terminal:

npm install react-router-dom

Step 3: Create Routes

Create a new file called Routes.js and add the following code:

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';

function Routes() {
  return (
    <BrowserRouter>
      <div>
        <h1>Navigation</h1>
        <ul>
          <li><Link to='/'>Home</Link></li>
          <li><Link to='/about'>About</Link></li>
        </ul>
        <Route path='/' exact component={Home} />
        <Route path='/about' component={About} />
      </div>
    </BrowserRouter>
  );
}

export default Routes;

Step 4: Render the Routes Component

Open the App.js file and replace the existing code with the following:

import React from 'react';
import Routes from './Routes';

function App() {
  return (
    <div>
      <Routes />
    </div>
  );
}

export default App;

Conclusion

You now have a basic understanding of how to use React Router for client-side routing in your React applications.

Keep going with react

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.