Rahul Sagore
Rahul Sagore

Reputation: 1668

React: location.state is undefined on first time navigating after page load

I have a React component, which display a Link:

Magic.tsx:

const { message } = this.props;
<Link to={ { pathname: HOGWARTS, state: { message } } }>
  Go to Page
</Link>

I am passing this Magic Component as a Prop to another component, where I am iterating over it, with Dynamic message state

Parent.tsx

const CustomComp = this.props.Magic;
const content = messageArray.map(msg => <CustomComp message={ msg } />)
{ content } //Render all the Links with message state

This is rendering the Link correctly. But when I click on the Link and debug the HOGWARTS page, the location.state is undefined. If go back to previous page, and click again, the location.state is correct, having message data. So somehow it's not working on page load, but after clicking on second time, it works.

Did anyone faced the same issue?

Note: I've inspected the <Link /> tag using React Devtool, on sidebar it shows that, what message state is attached to this link.

Upvotes: 1

Views: 5103

Answers (2)

Hong Zong
Hong Zong

Reputation: 21

’state‘ match 'BrowserRouter','hash' match 'HashRouter',so if you use 'HashRouter' match 'hash', 'state' must be undefined

Upvotes: 2

Nischith
Nischith

Reputation: 166

You just need to handle your state: { message } undefined case like below , as the state will be available only when the Link is clicked

So location.state is undefined at initial .

In your Parent.tsx

You can do something like this ..

const message =
            (this.props.location.state && this.props.location.state.message) != undefined
                ? this.props.location.state.message
                : " ";

And then use it

const content = messageArray.map(msg => <CustomComp message={ msg } />)

This should help you .. :)

Upvotes: 0

Related Questions