4

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;

5 Answers 5

4

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

You can define route as follows:

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

In component :

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

Comments

0

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 

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.