DEV Community

Cover image for Create A React Router App in 5 Minutes
ayubf
ayubf

Posted on

Create A React Router App in 5 Minutes

    Have you ever created a React app and wondered what it would take to add routes? Have, let's say, a seperate
page for your posts and pictures? Routes are a basic concept in web development and are necessary for any web development framework, frontend or backend. This is especially essential for RESTful APIs that take advantage of the ability for routes to output different pages, carry out different functions like logging in, logging out, etc. In this article I'll show you how to set up routes in React with a library called React Router.

Before you can start you should make sure you have the proper packages and tools installed.

Node & NPM

    Node is the environment that runs JavaScript frameworks and libraries like React and is essential for projects like these. NPM is the package manager for Node, and that basically means NPM installs the required files to use React and other libraries. We will use it later in this article to install libraries.

Install Node.js

Text Editor

    To put it simply, a text editor is just the application on your computer that will edit the text files to create the React app. My personal choice is one called VSCode, but there are other good options like Sublime Text, Notepad++, & Atom, but even your default text editor can get the job done.

Install VSCode

Step 1: Creating React App

    To initiate the React app we'll use a tool that's gonna make the process much simpler. Run the command below to create the React app.

npx create-react-app reactrouterapp
Enter fullscreen mode Exit fullscreen mode

npx is a package bundled with npm and is used to execute.

cd reactrouterapp
Enter fullscreen mode Exit fullscreen mode

cd will move us into the directory for the React app.

npm i react-router react-router-dom
Enter fullscreen mode Exit fullscreen mode

This command installs the required packages for this app.

Step 2: Adding Routes

    In this step we will create the app's routes and route outputs. First open the /src folder inside the reactrouterapp directory.
Create a new file named Page.js and type the following

    function Page() {
        return(
            <h1>This is the Page component</h1>
            );
    }
    export default Page;
Enter fullscreen mode Exit fullscreen mode

    The function Page() returns a JSX object in its' return statement. The export default statement at the bottom lets us use this in other files, very convenient.

Next, change the contents of App.js to the following:

import { BrowserRouter as Router, Routes, Route} from "react-router-dom";
import Page from './Page'

    function App() {
      return (
        <div className="App">
          <Router>
            <Routes>
              <Route path="/page" element={<Page />} />
            </Routes>
          </Router>
        </div>
      );
    }

    export default App;
Enter fullscreen mode Exit fullscreen mode

    The first line imports from the React Router library, and it imports three components for our routing

import { BrowserRouter as Router, Routes, Route} from "react-router-dom";
Enter fullscreen mode Exit fullscreen mode

    The second line imports from our Page.js file from earlier, and it imports the <Page /> component we created earlier.

The function App() returns this:

        <div className="App">
          <Router>
            <Routes>
              <Route path="/page" element={<Page />} />
            </Routes>
          </Router>
        </div>
Enter fullscreen mode Exit fullscreen mode

    Routes holds the routes and with the path= parameter can have a prefix. <Route> defines the specific routes, their paths, and the elements rendered (in this example that's our <Page /> component).

The app will return the <Page /> element when the /page route is visited.

Step 3: Running

To run the app run the follow command:

$ npm start
Enter fullscreen mode Exit fullscreen mode

The out put should be something like this.

    Compiled successfully!

    You can now view reactrouterapp in the browser.

      Local:            http://localhost:3000
      On Your Network:  http://10.0.0.87:3000

    Note that the development build is not optimized.
    To create a production build, use npm run build.

    assets by status 6.93 KiB [cached] 1 asset
    assets by chunk 1.6 MiB (name: main)
      asset static/js/bundle.js 1.53 MiB [emitted] (name: main) 1 related asset
      asset main.cdf5e8aba95c1b3dac48.hot-update.js 71.4 KiB [emitted] [immutable] [hmr] (name: main) 1 related asset
    assets by path *.json 611 bytes
      asset asset-manifest.json 583 bytes [emitted]
      asset main.cdf5e8aba95c1b3dac48.hot-update.json 28 bytes [emitted] [immutable] [hmr]
    asset index.html 1.67 KiB [emitted]
    Entrypoint main 1.6 MiB (1.62 MiB) = static/js/bundle.js 1.53 MiB main.cdf5e8aba95c1b3dac48.hot-update.js 71.4 KiB 2 auxiliary assets
    cached modules 1.41 MiB [cached] 107 modules
    runtime modules 31.3 KiB 15 modules
    javascript modules 3.95 KiB
      ./src/index.js 1.81 KiB [code generated]
      ./src/App.js 2.14 KiB [built] [code generated]
    webpack 5.67.0 compiled successfully in 75 ms
Enter fullscreen mode Exit fullscreen mode

    Visit the link in the output, either one of them, and then visit the /page route and you should see something like this.

Successfully run React app with React Router

    Congrats! You quickly created a React app with routes using React Router. Understanding & using routes and routing is a crucial skill for a wev developer, this will come up often in projects or on the job.

Sources

React Router v6
Create-React-App
React
Node.js
Npm
VSCode
Npx

Discussion (0)