Vaibhaw kr
Vaibhaw kr

Reputation: 161

How to render props conditionally and checking for undefined, while passing props via React useHistory?

I have component1 where I am redirecting user to other page and passing props like this

onClick={() =>history.push({pathname: "/student/planandprice", state: {plan: history.plan.courseName, as:history.availableSession}})}>Upgrade</Button>

So I want to render it on component2 only when its not undefined, its not undefined when i navigate from component1 to component2 via onclick because history.push(useHistory) method is executed. But I navigate directly to component 2, I get undefined error. I tried to check undefined values using condition: {props? props.location.state.as : ""} but its still not working and gives "Cannot read property 'as' of undefined" so how to check undefined values and render it conditionally?

Upvotes: 0

Views: 325

Answers (1)

rpie3
rpie3

Reputation: 146

Try using optional chaining: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

{props ? props?.location?.state?.as : ""}

Upvotes: 2

Related Questions