You read the title, and you know why you’re here! Want to make protected react routes in 2020? Let’s go! (You need to be familiar with the router already to follow this guide)

First have a react project. I like to separate my router from my app.js file into its own router.js file. My app.js file looks like this:

//App.js
import './App.css'
import React from 'react'
import Router from './components/application/router.js'
export default function App() {
  return (
    <div className='App'>
      <Router />
    </div>
  )
}

That’s right, I don’t use semicolons; except in my English.

Let’s set up the router.js file:

//router.js
//pretend we imported all of our components
import React from 'react'
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'
export default function Router() {
  return (
      <BrowserRouter>
        <Navigation /> 
        // I like to put my nav links into a seperate file
          <Switch>
            <Route exact path='/'>
              <PublicComponent />
            </Route>
          </Switch>
      </BrowserRouter>
  )
}

#react-router #javascript #react

Use Authentication To Protect React Routes
1.40 GEEK