DEV Community

Gabriel Neto
Gabriel Neto

Posted on

React authentication with Context API and React Router v6 (Typescript)

Creating a new project

Firstly we'll create a new React project with Vite, but you can choose the best option for you.
To start a new project we'll use the command below:



#npm
npm create vite@latest my-auth-app --template react-ts

#yarn
yarn create vite my-auth-app --template react-ts


Enter fullscreen mode Exit fullscreen mode

After this we need to install all dependencies generated by Vite.
To do this we'll run:



#npm
npm install

#yarn
yarn


Enter fullscreen mode Exit fullscreen mode

Well, now we have started our project and have all dependencies installed right.
You will have a folder structure like this in your project:
Image description

Before we start to code we'll delete some files from our project to make it cleaner like this:
Image description

Do not forget to delete all lines of code that depended of this deleted files

Now, lets install react-router-dom to create our routes.



#npm
npm install react-router-dom
npm install @types/react-router-dom -D

#yarn
yarn add react-router-dom
yarn add @types/react-router-dom


Enter fullscreen mode Exit fullscreen mode

Done! Now we can start coding our components and context.

Creating our project pages

Basicly in this example we'll need a login page and a homepage that can only be accessed if you are loged in.

I'll start creating a simple homepage like this:
Image description

And my login page like this:
Image description

Creating our Routes

I started creating our login route like this
Image description

Passing the Routes component inside our App.tsx
Image description

If you run your app you will get this in /login route:
Image description

Creating context

Image description

Setting up our Private Routes

Image description

Using context inside Login page

Image description

Done! Now when you click on the Authenticate button in Login page you will set up the authenticated state to true and will be redirected to Homepage.

This simple project can be find out in github:
https://github.com/GabrielDNeto/React-Authentication-ContextAPI---react-router-dom

Top comments (5)

Collapse
 
dvtrlf profile image
daia

Amazinggg!!! Thanks! 👏🏻👏🏻

Collapse
 
gabrieldneto profile image
Gabriel Neto

you're welcome my love 💜

Collapse
 
touilfarouk profile image
Farouk Touil • Edited

What is the name of the Vscode theme please?

Collapse
 
gabrieldneto profile image
Gabriel Neto

The name is Community Material Theme, but when you install, you will get a bunch of versions, i'm using the Palenight.

Image description

Collapse
 
valyek0 profile image
Illus1on

may be Tōkyō night