Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router grab URL segment in component

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.

like image 945
CyberJunkie Avatar asked Feb 11 '26 13:02

CyberJunkie


2 Answers

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>;
  }
}
like image 132
Tholle Avatar answered Feb 13 '26 02:02

Tholle


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;
like image 34
Lahiru Lanka Rathnayaka Avatar answered Feb 13 '26 01:02

Lahiru Lanka Rathnayaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!