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
After this we need to install all dependencies generated by Vite.
To do this we'll run:
#npm
npm install
#yarn
yarn
Well, now we have started our project and have all dependencies installed right.
You will have a folder structure like this in your project:
Before we start to code we'll delete some files from our project to make it cleaner like this:
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
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:
Creating our Routes
I started creating our login route like this
Passing the Routes component inside our App.tsx
If you run your app you will get this in /login route:
Creating context
Setting up our Private Routes
Using context inside Login page
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)
Amazinggg!!! Thanks! 👏🏻👏🏻
you're welcome my love 💜
What is the name of the Vscode theme please?
The name is Community Material Theme, but when you install, you will get a bunch of versions, i'm using the Palenight.
may be Tōkyō night