Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values from url using React

Tags:

reactjs

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;
like image 611
James Avatar asked Sep 08 '25 07:09

James


1 Answers

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>
  );
}
like image 67
0xc14m1z Avatar answered Sep 10 '25 08:09

0xc14m1z