Published

- 6 min read

Enrutador AuthGuard React V6

img of Enrutador AuthGuard React V6

Firebase, ReactJs, React Router — Protected Routes

Integrating authentication functionality in ReactJs with React Router was a bit complicated, The main reason is there is not any pre-define structure for integration. You can define your own structure. So here I have show you some useful stuff for Authentication AuthGuard.

As usual there are 3 kind of routes in website,

First one, those are under authentication, Like /profile, /dashboard or /settings etc…

Second one, where we user must not Logged In, if you are logged in then you can not visit that page, Like /login, /register & /forgot-password etc…

Last one is, it does not matter you are logged in or not, you can visit any how Like /blogs, /about-us etc…

Actually, In this integration I have create two Guards for routes,

First one is AuthGuard, used to check the user must logged in.

Second one is UnAuthGuard, used to check the user must not logged in.

Hope so, you understand the base concept, what we are going to implement, we have used here Firebase dependency for authentication, so you also learn how to implement easily.

Lets start….

What you will see…

  • Create React App
  • Integrate Routing and Guard Components
  • Design Login, Register, Welcome Page
  • Setup Firebase Project
  • Integrate Firebase & Authentication
  • Check The Progress

Create React App

  • We are using Node 16.
   > npx create-react-app react-router-auth-guard

Install Basic Dependencies

   > npm i react-router-dom firebase

Integrate Routing and Guard Components

  • Now we have react app ready & we have to integrate Routing and Guard

Lets Start from Guard Components

Create folder /src/guards

Create files /src/guards/AuthGuards.js & /src/guards/UnAuthGuards.js

AuthGuard.js

   import React, { useEffect } from 'react'

const AuthGuard = ({ component }) => {
	useEffect(() => {
		console.log('Auth Guard')
	}, [])

	return <React.Fragment>{component}</React.Fragment>
}

export default AuthGuard

UnAuthGuard.js

   import React, { useEffect } from 'react'

const UnAuthGuard = ({ component }) => {
	useEffect(() => {
		console.log('UnAuth Guard')
	}, [component])

	return <React.Fragment>{component}</React.Fragment>
}

export default UnAuthGuard

In the Guard component you can check we have just console log the guard, and return the component as it, for now it is enough for routing implement. After this routing we will writer the whole integration.

Need Pages Components

Now we have to create pages component for using in routing. We will have 3 pages. /login, /register & /welcome

  • Create folder /src/pages
  • Create files /src/pages/Login.js, /src/pages/Register.js & /src/pages/Welcome.js

Login.js

   import React, { useEffect } from 'react'

const Login = () => {
	useEffect(() => {
		console.log('Login')
	}, [])

	return <div> Login Form </div>
}

export default Login

Register.js

   import React, { useEffect } from 'react'

const Register = () => {
	useEffect(() => {
		console.log('Register')
	}, [])
	return <div> Register Form </div>
}

export default Register

Welcome.js

   import React, { useEffect } from 'react'

const Welcome = () => {
	useEffect(() => {
		console.log('Welcome')
	}, [])
	return <div> Welcome </div>
}

export default Welcome

We have return simple text for page component.

Routes Integration

Here we will create 2 separate list of routes and will add that routes to application routing.

Start from AuthRoutes

  • Create folder /src/routes
  • Create files /src/routes/AuthRoutes.js

AuthRoutes.js

   import React from 'react'
import { Route } from 'react-router-dom'
import AuthGuard from '../guards/AuthGuard'
import Welcome from '../pages/Welcome'

const AuthRoutes = [
	<Route key='Welcome' path='/' element={<AuthGuard component={<Welcome />} />} />
]

export default AuthRoutes

Currently we have only /welcome route under auth. So, this is the only one in list.

Second One UnAuthRoutes

  • Create folder /src/routes
  • Create files /src/routes/UnAuthRoutes.js

UnAuthRoutes.js

   import React from 'react'
import { Route } from 'react-router-dom'
import UnAuthGuard from '../guards/UnAuthGuard'
import Login from '../pages/Login'
import Register from '../pages/Register'

const UnAuthRoutes = [
	<Route key='Login' path='/login' element={<UnAuthGuard component={<Login />} />}></Route>,
	<Route key='Register' path='/register' element={<UnAuthGuard component={<Register />} />}>
		{' '}
	</Route>
]

export default UnAuthRoutes

As you see, we have 2 routes in unauth list /login & /register.

Also, check that we have attacked pages component in each routes item.

Add AuthRoutes & UnAuthRoutes to App component

App.js

   import './App.css'
import { BrowserRouter, Routes } from 'react-router-dom'
import AuthRoutes from './routes/AuthRoutes'
import UnAuthRoutes from './routes/UnAuthRoutes'

function App() {
	return (
		<div className='App'>
			<BrowserRouter>
				<Routes>
					{AuthRoutes}
					{UnAuthRoutes}
				</Routes>
			</BrowserRouter>
		</div>
	)
}

export default App

Yeah!! We have setup base. Lets test it……

Here We Go….

You must see these page, by calling below urls

:::

Dynamic HTML

Local variables can be used in JSX-like functions to produce dynamically-generated HTML elements:

   ---
const items = ['Dog', 'Cat', 'Platypus']
---

<ul>
	{items.map((item) => <li>{item}</li>)}
</ul>

Astro can conditionally display HTML using JSX logical operators and ternary expressions.

   ---
const visible = true
---

{visible && <p>Show me!</p>}

{visible ? <p>Show me!</p> : <p>Else show me!</p>}

Dynamic Tags

You can also use dynamic tags by setting a variable to an HTML tag name or a component import:

   ---
import MyComponent from './MyComponent.astro'
const Element = 'div'
const Component = MyComponent
---

<Element>Hello!</Element>
<!-- renders as <div>Hello!</div> -->
<Component />
<!-- renders as <MyComponent /> -->

When using dynamic tags:

  • Variable names must be capitalized. For example, use Element, not element. Otherwise, Astro will try to render your variable name as a literal HTML tag.

  • Hydration directives are not supported. When using client:* hydration directives, Astro needs to know which components to bundle for production, and the dynamic tag pattern prevents this from working.

Fragments

Astro supports using either <Fragment> </Fragment> or the shorthand <> </>.

Fragments can be useful to avoid wrapper elements when adding set:* directives, as in the following example:

   import React, { useEffect } from 'react'

const AuthGuard = ({ component }) => {
	useEffect(() => {
		console.log('Auth Guard')
	}, [])

	return <React.Fragment>{component}</React.Fragment>
}

export default AuthGuard

Differences between Astro and JSX

Astro component syntax is a superset of HTML. It was designed to feel familiar to anyone with HTML or JSX experience, but there are a couple of key differences between .astro files and JSX.

Attributes

In Astro, you use the standard kebab-case format for all HTML attributes instead of the camelCase used in JSX. This even works for class, which is not supported by React.

   <div className="box" dataValue="3" />
<div class="box" data-value="3" />

Multiple Elements

An Astro component template can render multiple elements with no need to wrap everything in a single <div> or <>, unlike JavaScript or JSX.

   ---
// Template with multiple elements
---

<p>No need to wrap elements in a single containing element.</p>
<p>Astro supports multiple root elements in a template.</p>

Comments

In Astro, you can use standard HTML comments or JavaScript-style comments.

   ---

---

<!-- HTML comment syntax is valid in .astro files -->{/* JS comment syntax is also valid */}

:::caution HTML-style comments will be included in browser DOM, while JS ones will be skipped. To leave TODO messages or other development-only explanations, you may wish to use JavaScript-style comments instead. :::

Related Posts

There are no related posts yet. 😢