0

I am using React and React Router.

Here is my first component:

import React from 'react';

class SomeClass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
              someObj: {
                something: "",
                someOtherThing: ""
              },
            authenticated: false
        };
    }

}



export default SomeClass;

Here is my ProtectedRoute component: const ProtectedRoute = ({auth, component: Component, ...rest}) =>{ return( <Route {...rest} render={(props) =>{

            if(auth){
                return(<Component {...props} />);
            }

            if(!auth){
                return(<Redirect to={{path: "/", state:{from: props.location}}} />);
            }
        }} />
    );
};

export default ProtectedRoute;

Here is my Nav component:

import React from 'react';
import { BrowserRouter as Router, Switch} from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import SomeClass from './SomeClass';

function Nav(){
    return(
        <Router>
            <Switch>
                <ProtectedRoute exact path="/somepage/abc" component={SomeClass} auth={SomeClass.props.authenticated} />  //getting an error here because of SomeClass.props.authenticated
            </Switch>
        </Router>

    );
}


export default Nav;

My Question:

In my Nav functional component, there is the <ProtectedRoute ....>, I want to get the authenticated value from the SomeClass's authenticated value (this.state.authenticated)?

When I do SomeClass.props.authenticated I get the following error:

TypeError: Cannot read property 'authenticated' of undefined

1
  • can you add what error you are getting? Commented Aug 10, 2021 at 18:23

1 Answer 1

1

you can pass it down in the form of a prop

in the someClass :

  • import Nav
  • type the following
<Nav auth = {this.state.authenticated}/>

and the Nav component should be as follows:

function Nav(props){
    return(
        <Router>
            <Switch>
                <ProtectedRoute exact path="/somepage/abc" component={SomeClass} auth={props.auth} /> 
            </Switch>
        </Router>

    );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.