Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get the value of {match.params.id} on react router

this is my code example but I do not know how to take the value and after use it

class View extends Component {
  componentDidMount() {
      var id = {match.params.id}
    }
    render() {
      return(
        <Router>
      <div>
        <Route path="/View/:id" component={Child}/>
      </div>
    </Router>
      )
    }
}
like image 791
Emmanuel Garcia Martinez Avatar asked Sep 14 '25 00:09

Emmanuel Garcia Martinez


2 Answers

This might help you. Just create constructor i.e constructor(props) {} and inside it declare the id as a state variable to the class. Pass the value of match.params.id to the id by using id: this.props.match.params.id.

Now u can access the state variable anywhere in your code and hope it solves your problem.

class View extends Component {
    constructor(props){
        super(props);

        this.state = {
            id : this.props.match.params.id
        }
    }
  componentDidMount() {
      var id = {this.state.id}
    }
    render() {
      return(
        <Router>
      <div>
        <Route path="/View/:id" component={Child}/>
      </div>
    </Router>
      )
    }
}
like image 171
Ujjawal Raj Avatar answered Sep 15 '25 14:09

Ujjawal Raj


You can do it this way :

import { useParams } from 'react-router-dom';

function GetId() {
    const { id } = useParams();
    console.log(id);
    return (
        <div>
           your expected id : {id}
        </div>
    );
}
like image 41
Mahadi Hassan Avatar answered Sep 15 '25 15:09

Mahadi Hassan