Search code examples
javascriptreactjsreact-propsdestructuring

How to redirect to another page if prop is not defined in react


I have a component that receives props and displays the received props. So I decided to load this page url without receiving a prop and I get this error:

   TypeError: Cannot destructure property 'myImage' of '(intermediate value)(intermediate value)(intermediate value)' as it is undefined.

So I tried to redirect the page if the props is not received (if it is undefined) with the following lines of code:

    componentDidMount(){
        if(this.props.location.myInfo === undefined){
            this.props.history.push('/');
            return;
        }
        this.setState({ name: this.props.location.myInfo });
    }
   render(){
      const { myImage, myName, myJobType, myPrice } = this.props.location.myInfo ? this.props.location.myInfo : this.props.history.push('/');
      return(
         <div>
            ...
         </div>
      )
   }

But none of these works. Been on it for hours trying different methods but none is working, how can I get if fixed?


Solution

  • You need more than one line to do this:

    1. Destructure this.props.location.myInfo and add optional value {}.

    2. Call this.props.history.push if this.props.location.myInfo is undefined.

    render(){
          const { myImage, myName, myJobType, myPrice } = this.props.location.myInfo || {};
          if(!this.props.location.myInfo) {
              this.props.history.push('/')
          }
          return(
             <div>
                //...
             </div>
          )
       }
    
    

    or

    
    componentDidMount() {
      if(!this.props.location.myInfo) {
         this.props.history.push('/')
      }
    }
    
    render(){
      const { myImage, myName, myJobType, myPrice } = this.props.location.myInfo || {};   
      return
      (
         <div>
            //...
         </div>
      )
    }