James
James

Reputation: 767

Extract values from url using React

I'm using React and I need to navigate the user to a profile page, i.e. mydomain.com/profile/myusername but I'm not sure how to extract the 'myusername' from the url? Snippet of my code are below, please help!

Many thanks

Routing

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div>
                    <Route path="/" component={Main} exact />
                    <Route path="/profile" component={Profile} exact />
                </div>
            </BrowserRouter>
        );
    }
}

export default App;

My hyperlink

<Link to={`profile/${obj.username}`}>{obj.username}</Link>

My profile page

import React, { Component } from 'react';

class Profile extends Component {

  componentDidMount() {
  }

  render() {

    return (
      <div>
        <h1>myusername</h1>
      </div>
    );
  }
}

export default Profile;

Upvotes: 4

Views: 6038

Answers (5)

Kazi
Kazi

Reputation: 391

For the recent Typescript versions, we have to specify the name and type of the param we want to use.

URL:

    http://localhost:3004/user-detail/:username

The following way can be used:

    const {username} = useParams<{ username: string }>();

Alternative option 1:

    const { username } = useParams() as { 
        username: string;
    }

Alternative option 2:

Declaring an interface:

    interface ParamInterface {
        username: string;
    }

Then using that interface inside the component:

    const { username } = useParams<ParamInterface>();
    

Alternative option 3:

    const { username } : any = useParams();

Upvotes: 1

Jamviet.com
Jamviet.com

Reputation: 306

There are two ways to do: first via useParams() in react-router-dom or via props:

<Route path="/profile/:username" component={Profile} exact />

And get it via:

const username = props.match.params.username || null

But i prefer using default useParams() in react-router-dom:

let useParam =  {} as any;
    useParam = useParams();
    let Param = useParam.any || false;

Good day!

Upvotes: 0

shradha
shradha

Reputation: 481

You may define your route as follows,

<Route path="/profile/:username" component={Profile} exact />

Then access username in your component,

this.props.match.params.username 

Upvotes: 0

Umair Farooq
Umair Farooq

Reputation: 1823

You can define route as follows:

<Route path="/profile/:id" component={Profile} exact />

In component :

const id = this.props.match.params.idj

Upvotes: 0

0xc14m1z
0xc14m1z

Reputation: 3725

You have to declare your route like:

<Route path="/profile/:username" component={Profile} exact />

And then in your component you can access the username with:

this.props.match.params.username

Like this:

render() {
  return (
    <div>
      <h1>{ this.props.match.params.username }</h1>
    </div>
  );
}

Upvotes: 4

Related Questions