-1

I set a Component state with data from this.props.location.state. How can I redirect if it's null.

My Application has 2 routes:

<BrowserRouter>
    <Switch>
       <Route path="/comp2" component={Comp2} />
       <Route path="/" exact component={Comp1} />
    </Switch>
</BrowserRouter>

From Comp1 I can go to Comp2.

<Link to={{ pathname: "/comp2", state: {values} }}>{values.description}</Link>

Then, I set my state in the Comp2 with this data:

constructor(props) {
    super(props);
    this.state = {
        data: this.props.location.state.values
    };
}

It's working. However, if in the browser, I go straight to http://localhost:3000/comp2, it fails. How can I redirect back to http://localhost:3000 if the this.props.location.state.values is null?

Thanks

myTest532 myTest532
  • 1,451
  • 10
  • 24

1 Answers1

0

Try this :

const data = this.props.location.state ? history.location.state.values : ''

in return (

<>
{data ? 
       <div> //ur comp2 component dom </div>
       : 
       <Redirect to="/homePage" />
}
</>
)
Madhuri
  • 239
  • 1
  • 7