Keyz23
Keyz23

Reputation: 81

ReactJS: React-Router pass value to another page

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?

Upvotes: 0

Views: 416

Answers (1)

Rostyslav
Rostyslav

Reputation: 2866

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()
  }
}

Upvotes: 1

Related Questions