I'm using a simple router in React
<Router>
<div>
<Switch>
<Route path="/" component={ Home } exact />
<Route path="/contact" component={ Contact } />
<Route path="/:slug" component={ Post } />
</Switch>
</div>
</Router>
I'm pulling posts from a blog using REST and have a router component named Post for single blog posts. Any Route that doesn't match with home or contact, uses the post component.
How can I get or pass the route slug/url segment in the Post component? For example if the url segment/slug is /some-blog-post-title, I want to retrieve it, preferably using a React Router function/method if it exists.
You can get the parameters in the props.match.params object. To get your :slug parameter you would write props.match.params.slug.
Example
class Post extends React.Component {
componentDidMount() {
this.getPost(this.props.match.params.slug);
}
componentDidUpdate(prevProps) {
if (prevProps.match.params.slug !== this.props.match.params.slug) {
this.getPost(this.props.match.params.slug);
}
}
getPost = slug => {
// ...
};
render() {
return <h2>{this.props.match.params.slug}</h2>;
}
}
If you want to grab urls in a functional component
App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import User from './User';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/user/:userName' component={User} />
<Route>
<div>Default page</div>
</Route>
</Switch>
</Router>
);
}
}
export default App;
Inside the functional component you can grab it
import React from 'react';
import { useParams } from 'react-router-dom';
const User = () => {
const { userName } = useParams();
return (
<div>Username: { userName }</div>
);
}
export default User;
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