'How to get data from prop.location.state in react?

I try to send data through history push like that. enter image description here

And then I try to get the value of id that I send. enter image description here

The problem is when the first time rendering of component, I got the value of undefined. And then when I click the previous button on browser then I got the value. Why could be happened ???



Solution 1:[1]

Default state is missing, so use componentDidMount life cycle and inside componentDidMount call default state.

Solution 2:[2]

send params in the url.

Define the route

<Route path="/bookingform/:id" component={BookingForm} />

and then in the component you can get the id by props.match.params.id

Solution 3:[3]

It would help if I could see how you're writing your component.

to make this code work, this should help.

<Route exact path="" render= {routeProps => (<theComponent {...routeProps} />)}

Solution 4:[4]

You can pass a state to push method as the second parameter, push(url, state) not push({ pathname, state}) .Example below

// Home.jsx
const Home = (props) => {
  // the second value in push method is the state
  handClick = () => props.history.push('/login', { comingFromHome: true })
  return <HomeBigOrSmallComponent onClick={handleClick} />
}

then, access the state

// Login.jsx
const Login = (props) => {
  // now let's log our state
  useEffect(() => console.log(props.history.location.state.comingFromHome), [])

  return <LoginBigOrSmallComponent onClick={handleClick} />
}

History objects typically have the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:
    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation (see the history docs)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nikhil bhatia
Solution 3 Musaddiq R. Mashrur
Solution 4 Akolade Adesanmi