johnboy
johnboy

Reputation: 111

React - Cannot Read Property 'params' Of Undefined

I set params in Route. They appear in the console from my component but I get an "undefined" error.

<Router>
    <App>
        <Switch>
                <Route exact path='/data/:param' component={data} />
        </Switch>         
    </App>
</Router>

component

class Data extends Component {
    constructor(props) {
        super(props);

    async componentDidMount() {
        console.log(this.props.match.params.param)

    ...

export default Data;

If I can see them in the console why do I still get an error?

Unhandled Rejection (TypeError): Cannot read property 'params' of undefined

enter image description here

Upvotes: 0

Views: 4330

Answers (1)

Rachita Bansal
Rachita Bansal

Reputation: 106

You need to make sure your import is correct for the Route which is Data.

import Data from './Data';
...
     <Route exact path='/data/:param' component={Data} />
...

You don't need to wrap the component with withRouter higher order component since your component Data is already a child of Route.

FWIW do

componentDidMount() {
  console.log(this.props.match && this.props.match.params.param);
}

Also, you probably don't need the async while doing componentDidMount(). This also could be the reason you need to add the defensive code as given above.

PS: console.log() can show evaluated data which is usually represented with an i just besides the object eval.

Upvotes: 2

Related Questions