Skip to content Skip to sidebar Skip to footer

How To Use 'this.props.params' In React?

I send a certain id (idValue) to my component and use it like this: componentDidMount() { this.onHandleFetch(this.props.params.idValue); } But sometimes this component opens

Solution 1:

The error tells us that this.props.params is undefined sometimes (probably because no params was passed to the component at all).

How can I fix it?

It depends on whether you want to call this.onHandleFetch if there's no params.idValue.

If you don't, use an if:

componentDidMount() {
  if (this.props.params && this.props.params.idValue) {
    this.onHandleFetch(this.props.params.idValue);
  }
}

If you do, providing some replacement value, then:

componentDidMount() {
  this.onHandleFetch((this.props.params && this.props.params.idValue) || replacementValue);
}

Both of those assume idValue won't be 0.

Solution 2:

static defaultProps = {
    params:{}
}

Solution 3:

Add appropriate default props to the component where you are trying to access the params e.g.

MyComponent.defaultProps = {
  params: {}
};

This will mean that when you try to access params from componentDidMount(), this.props.params will not be empty if you did not pass in an object for params like so when using the component.

  1. with params <MyComponent params={{ idValue: 1 }} /> will use the params passed here.
  2. without params <MyComponent /> will fallback to the defaultProps above.

You will only need to check for the presence of ID in that case to make sure that your component only makes the fetch if an idValue is defined in the params.

componentDidMount() {
    const { params } = this.props;
    if (params.idValue)
        this.onHandleFetch(params.idValue);
    }
}

Alternatively, you can pass a default value if idValue is not defined e.g.

componentDidMount() {
    const { params } = this.props;
    this.onHandleFetch(params.idValue || -1);
}

Post a Comment for "How To Use 'this.props.params' In React?"