How to get url parameters in reactjs

Viewed 888

I have two components: App and Contact. I just want to print the id on contacts page that I'm passing in the route, but when I console.log(this.props) in my contact component, it's showing an empty object.

import React from "react";
import Contact from "./Contact";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

class App extends React.Component {
  render() {
    return (
      <Router>
        <ul>
          <li>
            <Link exact to="/">
              Home
            </Link>
          </li>
          <li>
            <Link to={"/contact/id=" + 5}>contact us</Link>
          </li>
        </ul>

        <Route exact path="/">
          Home
        </Route>

        <Route path="/contact">
          <Contact />
        </Route>
      </Router>
    );
  }
}

export default App;
import React from "react";

class Contact extends React.Component {
  render() {
    {console.log(this.props);}
    return <div>contact page</div>;
  }
}

export default Contact;

how to console.log(this.props.match)?

4 Answers

You could pass it into the Contact component like so:

<Route path="/contact">
    <Contact id={5}/>
</Route>

and inside of your Contact component:

If you are using classes

this.props.id

If you are using functions

function Contact({id, ...props}){
// id === 5
}

It is worth noting that this is still javascript and you could get the URL parameters the same way you would in vanilla JS like so: (if you wanted to, although it is not advised):

let id = (new URL(window.location.href)).searchParams.get('id');

Hope this helps,

You're declaring your parameters incorrectly

<Route path='/foo/:bar' component={Foo} />

And inside Foo

const Foo = ({ match }) =>{
    const = { params:{bar} } = match

    console.log(bar)
}

If you access like /foo/content bar will assert to content

I figured it out. I wrapped my HOC with withRouter() and the problem gets solved :)

Dead simple way two liner solution which will work for regardless of clsss & functional components

const params = new URLSearchParams(window.location.search); // add on top under import
console.log(params.get('catid'));

I literally don't know why its not mentioned

Related