HOW TO SETUP A REACT APPLICATION WITH ROUTER, NESTED ROUTES, ERROR HANDLING, AND CONTEXT
Tags: react, webdev, frontend
Published: 2023-04-13 23:01:53


In this article I will show you how to set up a simple react application with the following implemented: React-router, Nested routes, 404 page, and Error boundary. Fake userAuthContext using the context API to always carry out a fake authentication. Navigation menu that will show on each page.

Link to this application [here](https://my-exam-project-teffa.netlify.app)

## TABLE OF CONTENTS

1. Pre-requisites
2. Getting Started With Your App
3. What Is React?
4. Setting Up React
5. Components
6. React-Router
7. 404 Page & Error Boundary
8. 404 Page
9. Error Boundary
10.Fake UserAuthContext Using Context Api
11.Conclusion

## Pre-requisites
To understand this blog post, you need to have basic knowledge of the following:
HTML
CSS
JavaScript
React Js

### APPLICATIONS USED:
Vscode
Github
Netlify
N/B: I used a MacBook to setup this application. Downloading dependencies on windows may be a bit different.

## Getting Started With Your App

To get started you need to set up and download all dependencies.

- Node JS – nodejs.org
- VS Code Editor – code.visualstudio.com/download
- Prettier Code Formatter Extension in VS Code
- React
- React Router

When Node Js is installed, it comes with a package manager called npm, which allows you access to bits of code that other developers have already written. To check if both Node.js and npm were installed successfully, open up your terminal and simply type the following code below:

```
node -v
npm -v
```
If your code runs and shows you the version of both npm and Node.js, it means installation was successful.

## What Is React?

React is an open source JavaScript front-end framework . It is used for building fast and interactive user interfaces for the web, as well as mobile apps.

### Setting Up React

You have all the dependencies installed, open your terminal and follow the steps below:
Change directory into the folder you want your project to be in. I used a Documents folder

```
cd Documents
```
Create a new directory for your app in your Documents folder

```
mkdir ReactApp
```
Change directory to the new folder you created with the code above

```
cd ReactApp
```
Create your react app with the code below, give it your own app name. I used “myreactapp”

```
npx create-react-app myreactapp
```
Now you have successfully created a react application. Follow this next step

```
cd myreactapp
```

```
npm start
```
This is a shortcode that opens your new application in Vs Code automatically.

```
code.
```
Components

Go to your src folder and create a components folder. Create all the components for your application with the necessary linking.

## React-Router
To install, go to your terminal and type the code below:

```
npm install react-router-dom@6
```
Our app has 4 pages we would be routing: Home page, About Page, Login Page and an Error Page. Create Components for each page.
Open you App.js file in VS Code and import BrowserRouter, Route and Routes

```
import { BrowserRouter, Route, Routes } from "react-router-dom";
```
Route all the components that require routing.

```
function App() {
  return (
    <section>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Home />}  />  
            <Route path="/Login" element={<Login />} />
            <Route path="/About" element={<About />} />
            <Route path="/Error" element={<Error />} />
            <Route path="*" element={<PageNotFound />}  />  
          </Routes>
        </BrowserRouter>
    </section>
  );
}
```

## 404 Page & Error Boundary

### 404 Page

A 404 page is known as an “error page” or “page not found” page. It is usually indicative of a page that doesn’t exist. It is important to create a 404 page on your website with the necessary information and link to re-direct visitors, so they don’t lose interest.
Start by creating a “PageNotFound.js” component, route it in your app.js, as shown in the code above.

```
import React from "react";
import sad from ".//image/sad.PNG";
import { Link } from "react-router-dom";

export default function PageNotFound() {
  return (
    <section className="notfound-container">
      <div className="content-container">
        <img src={sad} alt="sad" />
        <h1>404 Error</h1>
        <p>Page Not Found</p>
        <p>
          The page you are looking for doesn't exist or an error occured. 
          <p><Link to="/">Go back to home page</Link></p>
        </p>
      </div>
    </section>
  );
}
```

### Error Boundary
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

```
class ErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
  
    static getDerivedStateFromError(error) {
      return { hasError: true };
    }
  
    componentDidCatch(error, errorInfo) {}
  
    render() {
      if (this.state.hasError) {
        return <h1>Something went wrong.<Link to='/'>Go back to home page</Link></h1>;
      }
  
      return this.props.children;
    }
  }
```
Wrap your app in the ErrorBoundary tag.

```
function App() {
  return (
    <section>
      <ErrorBoundary>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/Login" element={<Login />} />
            <Route path="/About" element={<About />} />
            <Route path="/Error" element={<Error />} />
            <Route path="*" element={<PageNotFound />} />
          </Routes>
        </BrowserRouter>
      </ErrorBoundary>
    </section>
  );
}
```

## Fake UserAuthContext Using Context Api
In this section we will be creating a login page that provides the implementation for authenticating users.
Create a AuthUser.js component and implement the following code.

```
import { createContext, useState, useContext} from "react";

const userAuthContext = createContext({});

export const AuthUser = ({ children }) => {
  const [auth, setAuth] = useState({});

  return (
    <userAuthContext.Provider value={{ auth, setAuth }}>
      {children}
    </userAuthContext.Provider>
  );
};

export default userAuthContext;

export const useAuth = () => {
    return useContext(userAuthContext)
  }
```

In your Login.js component, create a login form. UseState is used to create the state of the page. After login, the user gets to see their login details and a link that redirects you to the homepage.

```
import React from "react";
import { useState, useContext } from "react";
import { Link } from "react-router-dom";
import userAuthContext from "./Context/AuthUser";
import Navigation from "./Navigation";

const Login = () => {
  // eslint-disable-next-line no-unused-vars
  const { setAuth } = useContext(userAuthContext);
  const [user, setUser] = useState("");
  const [pwd, setPwd] = useState("");
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    setSuccess(true);
  };

  return (
    <>
      <div>
        <header>
          <Navigation />
        </header>
      </div>
      {success ? (
        <section>
          <h3>
            You are logged in as, <span>{user}</span>.
          </h3>
          <br />
          <p>
            <Link className="link" to="/">
              Go to home page
            </Link>
          </p>
        </section>
      ) : (
        <div className="main">
          <div className="sub-main">
            <div className="imgs">
              <div className="container-image">
                <img src={loginimg} alt="loginimg" className="profile" />
              </div>
            </div>

            <div className="logginn-container">
            <h1>Login Page</h1>
            <form onSubmit={handleSubmit}>
              <div>
                <input
                  type="text"
                  id="username"
                  placeholder="Enter Username"
                  className="name"
                  autoComplete="off"
                  onChange={(e) => setUser(e.target.value)}
                  value={user}
                  required
                />
              </div>

              <div>
                <input
                  type="password"
                  id="password"
                  placeholder="Enter Password"
                  className="name"
                  onChange={(e) => setPwd(e.target.value)}
                  value={pwd}
                  required
                />
              </div>
              <div className="button-container">
                <button className="login-button">Log In</button>
              </div>
            </form>
          </div>

          </div>
          
        </div>
      )}
    </>
  );
};
export default Login;
```

## Conclusion
Great job on getting to the end of this blog post. You can now create a simple react application that implements React-router, Nested routes, 404 page, and Error boundary etc. With practice you would be able to do it yourself without any help.
To view a life demo of this project, click here, you can also find the source code on Github.
Share you thoughts in the comments.