Private routes with reactjs?

Asked

Viewed 212 times

0

I’m trying to create private routes with ReactJs, but always gives the same error, I’ve been on several sites and always do according to each tutorial, but still the same error continues:

My code is this:

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
  {...rest}
  render={props =>
    isAuthenticated() ? (
      <Component {...props} />
    ) : (
      <Redirect to={{ pathname: "/", state: { from: props.location } }} />
    )
  }
/>);

this is already one of the ways I found on a site, the error that is:

inserir a descrição da imagem aqui

Could someone help me with this problem?

1 answer

0


I have the code this way, I realized that in your have a parentheses in place of the keys, it may be this, I’m just guessing, but, right below there is the code that I use and that works perfectly, where isAuthenticated is the function that checks whether you are logged in or not, example:

import React from 'react';
import { Redirect, Route} from 'react-router-dom';

const isAuthenticated = () => localStorage.getItem('token');

export const PrivateRouter = ({component: Component, ...rest}) => {
    return (
        <Route
            {...rest}
            render={props => 
                    isAuthenticated() ? (
                        <Component {...props} />
                    ) : (
                        <Redirect to={{pathname:"/login", state: {from:props.location}}} />
                    )
                }
        />
    )
}

to use:

<PrivateRouter path={''} exact component={component} />
  • 1

    Blz, it worked here, at first glance it didn’t work looking at the parentheses as you had commented, but still gave error, so I put the isAuthenticated inside the file itself as you put there, so it worked, thanks for the help, I’ve been racking my brain for two days.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.