Basic Client-Side Authentication in REACT

Client-side authentication in react using hooks and routes

BASIC IDEA TO START WITH

import React,{useState} from 'react'function SignIn() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')

const handleEmail = (e) => {
setEmail(e.target.value)
}
const handlePassword = (e) => {
setPassword(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
}
return (
<div style={{ textAlign: 'center' }}>
<h1>Signin Page</h1>

<form onSubmit={handleSubmit}>
<label htmlFor='email'>
Email
</label>
<br />

<input
id='email'
type='email'
placeholder='Email'
onChange={handleEmail}
value={email}
/>
<br />
<label htmlFor='password'>
Password
</label>
<br />
<input
id='password'
type='password'
placeholder='Password'
onChange={handlePassword}
value={password}
/>
<br />
<br />
<button type='submit'>Signin</button>
</form>
</div>
)
}
export default SignIn
import React from 'react'

function Dashboard() {
return (
<div style={{ textAlign: 'center' }}>
<h1> This is the protected dashboard Page</h1>
<button >Logout</button>
</div>
)
}
export default Dashboard
import Home from './components/home'
import { BrowserRouter, Route, Switch} from 'react-router-dom'
import SignIn from './components/signin'
import Dashboard from './components/dashboard'
function App() {
return (
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/signin' component={SignIn} />
<Route exact path='/dashboard' component={Dashboard} />
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
const ProtectedRoute = ({ component: Component, ...rest }) => ( 
<Route {...rest} render={(props) => (
sessionStorage.getItem("token")
? <Component {...props} />
: <Redirect to='/signin' />
)} />
)

Enthusiastic Developer and Tech lover by heart. Loves to learn new technologies.