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

Viewed 39113

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

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

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

Try this:

<Route path=`/View/${id}` component={Child}/>

{match.params.id} like variable.

this.id = this.props.match.params.id;

this.apartament = json.find((entry) => entry.id === this.id);

Related