Cannot read property 'params' of undefined, React

Viewed 8263

I have a problem, I'm passing (IMO) in the props the right way, but I still have that error:

I have these lines of code in my App.js

This one is working:

           <Route path="/users/:username" 
               render={(props) => <Profile  isAuthenticated={this.state.isAuthenticated} currentUser={this.state.currentUser} {...props} />}>
           </Route>

But this one is not working, while rendering "Ride" I am getting an error

        <Route path="/ride/:username" 
          render={(props) => <Ride  isAuthenticated={this.state.isAuthenticated} currentUser={this.state.currentUser} {...props} />}>
        </Route>

Error: TypeError: Cannot read property 'params' of undefined

  43 |    }
  44 |      
  45 |    componentDidMount() {
> 46 |        const username = this.props.match.params.username;
  47 | ^      this.loadUserProfile(username);
  48 |    }
  49 | 

Even when the code is inside (components) they are the same...

3 Answers

I'm providing the solution for your current problem but depending on your purpose probably you want to change your code a little bit. You are getting undefined for your Ride component because there is an extra render for it. Here:

.....
    <div style={{ display: "flex", justifyContent: "center" }}>
        <h6>Made by Konrad Krukar</h6>
    </div>
    <Ride />   <-------- SEE
</Layout>
....

This is in your App component. Since it is not wrapped by a Router you can't get the desired props. I don't know what is the aim for rendering it but you can use withRouter maybe.

In some cases check if you wrapped component in withRouter

example with redux

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(ComponentName)
);

or just a functional component

export default withRouter(ComponentName);

Another alternative you can try is using the React developer tools (if you aren't already) and see what the props look like. The user above me also suggested logging it in the console, which can also help us figure out what the problem is. Right now, in the applications current state, it can't read the property 'match'.

If I'm reading this correctly, there is no prop called 'match' being passed to your component?

Related