Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

React Private Route

Private Route--------

import { Navigate,useLocation} from "react-router-dom"
function Protecte({auth, children }) {   
    return auth ? children : <Navigate to="/login" />;
   
}
export default Protecte
-----------------------------------

App.js---
<Route path="/admin" element={
            <Protecte auth={isLoggedIn}>
              <Admin />
            </Protecte>
    }
   />
Comment

react router dom private route

//WORKS ON react-router-dom v6
//Using Outlet and Navigate
import { Routes, Route, Outlet, Navigate} from "react-router-dom";

function PrivateOutlet() {
  const auth = useAuth();
  return auth ? <Outlet /> : <Navigate to="/login" />;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/private-outlet" element={<PrivateOutlet />}>
          <Route element={<Private />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
Comment

private route in react js

const PrivateRoute = ({component: Component, ...rest}) => {
  const {isAuthenticated} = rest;

  return (
    <Route {...rest} render={props => (
      isAuthenticated ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: {from: props.location}
        }}/>
      )
    )}
    />
  );
};

PrivateRoute.propTypes = {
  isAuthenticated: PropTypes.bool.isRequired,
};

function mapStateToProps(state) {
  return {
    isAuthenticated: state.user.isAuthenticated,
  };
}

export default connect(mapStateToProps)(PrivateRoute);
Comment

PREVIOUS NEXT
Code Example
Javascript :: add tailwind to vue 
Javascript :: array map arrow function 
Javascript :: todashcase javascript 
Javascript :: get count of class which is visible element 
Javascript :: javascript sleep 1 
Javascript :: javascript validate string with regex 
Javascript :: next router 
Javascript :: style scoped vue 
Javascript :: make copy of date javascript 
Javascript :: tinymce update textarea value using jquery 
Javascript :: tab adds tab textarea javascript 
Javascript :: javascript check if url returns 200 
Javascript :: how to access dictionary keys in js 
Javascript :: js how to check is array empty es6 
Javascript :: angular pipe percentage 
Javascript :: javascript onkeydown 
Javascript :: stop a site from reloading javascript 
Javascript :: window load 
Javascript :: scroll to top 
Javascript :: tick.json code 
Javascript :: jquery get dropdown list selected value 
Javascript :: create a download file from blob url 
Javascript :: jquery get 2nd child 
Javascript :: how to set the development mode in webpack 
Javascript :: promise all then 
Javascript :: lowercase to uppercase in javascript 
Javascript :: regular expression characters 
Javascript :: Converting string to json object 
Javascript :: mongodb find all that dont have property 
Javascript :: reset page js 
ADD CONTENT
Topic
Content
Source link
Name
5+3 =