1

I want to pass some value from one component to another once the user clicks a button.

First Component (Survey) with a value survey --> User clicks a button --> Second component (Details) renders the survey

To achieve so I am using Redirect from the react-router-dom.

function Survey({survey}) {
....
// There is a button that triggers the below if clause. The redirect works but it seems the state is not sent.
    if (surveyPage === true) {
        return <Redirect to={{
            pathname: '/detail',
            state: { location: survey }
        }}

    }

    return("something")

}

Second component

function Details(){
    console.log( this.props.location.state.location) // Cannot read property 'props' of undefined
    return "test"
}

Cannot read property 'props' of undefined

I tried also:

function Details({survey){
    console.log(survey) // Undefined
    return "test"
}

and

function Details({ location: survey }){
    console.log(survey) // Undefined
    return "test"
}

I am really not understanding what I am doing wrong. I am following the documentations: https://reacttraining.com/react-router/web/guides/primary-components

Prova12
  • 615
  • 5
  • 13
  • This is not about `react-route-dom`, it's about how to pass props property to functional component. Since the error is `props undefined` – keikai Feb 04 '20 at 08:38
  • I tried also without `this`, but still similar error – Prova12 Feb 04 '20 at 08:43

2 Answers2

3

this is not accessable in functional components. You need to do it like this:

import { useHistory } from "react-router-dom";

function Details(props){
    const history = useHistory();
    console.log(history.location.state.location);

    return <p>Test</p>
}

export default Details;

Hope this works for you.

Muhammad Zeeshan
  • 3,867
  • 2
  • 8
  • 31
1

To connect your component to the routes information, you should use the withRouter HOC or useHistory hook.

withRouter example:

import { withRouter } from "react-router";

function Details(props){
    console.log(props.history.location.state.location);

    return <p>Test</p>
}

export default withRouter(Details);
Ali Torki
  • 1,610
  • 12
  • 17