0

I am using React JS and React Router.

I have 2 classes:

  1. App.js
  2. SomeClass.js

in App.js:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            token: "",
            auth: false
        };
    }
    
    
    
    
    render(){

        return(
            <Router>
              
                <Switch>
                    <Route exact path="/anotherendpoint" component={() => <SomeOtherComponent auth={this.state.auth} token={this.state.token} />} />
                    <Route path="/someendpoint/abc" exact component={() => <SomeClass auth={this.state.auth} token={this.state.token} />} />
                </Switch>
            </Router>
            );
    }
    
}


export default App;

In SomeClass.js:

class SomeClass extends React.Component{
    constructor(props){
        super(props);
    }
    
    
    logout = () =>{
        console.log('token: ', this.props.token);   //getting token: undefined
        let myCookie = document.cookie;
        console.log("cookie: ", myCookie);      //getting cookie: undefined
    }


}

export default Nav;

In the SomeClass class, whenever I do this.props.token, I get undefined

Also when I console.log(document.cookie), I get undefined

The problem occurs only in the SomeClass component. What is the reason behind that ?

Why the props are undefined.

Thanks.

2 Answers 2

1

You pass props to component wrong way. Just add props to component like this:

component={() => <SomeComponent auth={this.state.auth} token={this.state.token} />}
2
  • What is undefined?
    – Viet
    Commented Aug 26, 2021 at 13:46
  • what is SomeClass? Nav?
    – Viet
    Commented Aug 26, 2021 at 13:54
0

Try this approach.

you can learn more here

https://reactrouter.com/web/example/basic

    <Router>
      <Switch>
        <Route path="/teste" exact>
          <SomeOtherComponent auth="AUTH PROP" token="FAKE_TOKEN_PROP" />
        </Route>
      </Switch>
    </Router>