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;
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With