4

I have a problem like this. I am developing a React application. There is an Url like this

http://localhost:3000/drivershow/0x6E2C0A2f1a7e8fb7C33b3826FF14F95C90535557

I want to access the 0x6E2C0A2f1a7e8fb7C33b3826FF14F95C90535557 part from the URL. To do that I have tried something like this by following some question in the StackOverflow.

import React, { Component } from 'react';
import queryString from 'query-string'

class DriversShow extends Component{
    async componentDidMount(props){
        const values = queryString.parse(this.props.location.search)
        console.log(values);
    }

    render(){
        return(
            <div>Haiiiiiiiiii</div>
        );
    }
}

export default DriversShow; 

But it consoles log undefined. Can someone help me to solve this problem? I tried some other examples by searching in the Google but those were unable to make a sense. Thank You!!

dwp
  • 908
  • 4
  • 24
  • 42

3 Answers3

1

Another way is the useParams(). React-Router introduce this since version 5.1 to easily get the url params, you can check the official example.

<Route path="/drivershow/:showid" component={DriversShow} />

Be careful that useParams() must be inside functional component.

import { useParams } from "react-router-dom"

function DriversShow(){
    const { showid } = useParams()
    ...
}
Bûn-lī
  • 23
  • 6
0

I think there was some misunderstanding about location.search vs location.params. The 0x6E2C0A2f1a7e8fb7C33b3826FF14F95C90535557 should be location.params. Could you provide us with your react-router's version?

If you are using V4, you should follow this example to get location params.

If you are using the older version, you can get request params inside the componentDidmount lifecycle like this:

componentDidMount () {
    const { handle } = this.props.match.params

    fetch(`https://api.twitter.com/user/${handle}`)
      .then((user) => {
        this.setState(() => ({ user }))
      })
  }
Vu Luu
  • 792
  • 5
  • 16
-1
<Route path="/users/:id" component={Hello} />

on componentDidMount used

this.props.match.params.id
Infomaster
  • 793
  • 7
  • 8