0

I have need to pass a value from a page to another using react-router.

I have tried in this way:

<li>
    <A 
      className="btn btn-link btn-sm"
      href={{ pathname: Routes.detail_page, search: `?_id=${C.Code}`, state: this.props.current  }}>
      { 'Open' }
    </A>
</li>

I would pass this.props.current to Detail Page.

In the other page if I tried in the componentDidMount() to print this.props.current it result undefined (of course in the first page this value is parametrized).

constructor(props){
    super(props);
    this.state = {
    };
  }
componentDidMount(){
    let C = this.props.current
    console.log("C is: ", C) // this is undefined
    this.updateIsDeletableState()
  }

How can I do?

6
  • could you add your "the other page code"? Commented Jun 25, 2020 at 8:29
  • I only have tried to print the this.props.current usign console.log in the componentDidMount(). What do you need to know? :) Commented Jun 25, 2020 at 8:31
  • I want to see how did you code. Commented Jun 25, 2020 at 8:32
  • I have edited the message Commented Jun 25, 2020 at 8:33
  • Make sure you have the following in your component where you are trying to access the props: ``` constructor(props){ super(props); this.state = { //states }; } ``` Commented Jun 25, 2020 at 8:35

1 Answer 1

1

You have to make sure that you have defined URL parameter in the Route

// file-where-you-define-routes.js
...
<Switch>
  <Route path={`your-path/:id`} component={YourComponent} />
</Switch>
...

Then use hook useParams to get the parameter

function YourComponent() {
  const { id } = useParams();
  let C = id;
  console.log("C is: ", C) // this should be defined now
  ...
}

OR if you use class component this.props.match.params.id

class YourComponent extends Component {
  ...
  componentDidMount(){
    let C = this.props.match.params.id; // match
    console.log("C is: ", C) // this should be defined now
    this.updateIsDeletableState()
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, the route can declaration can also be updated as following to pass the props <Route exact path="/props-through-render" render={(props) => <PropsPage {...props} title={Props through render} />} />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.