URL Parameters with React Router

This is part of our React Router v4 course. Check it out if you like this post.

URL parameters are a fundamental aspect of React Router and a fundamental aspect of building web applications. In this post, we’ll break down the “URL Parameters” example on the React Router documentation to learn how you to effectively leverage URL parameters in your React app.

URL parameters are parameters whose values are set dynamically in a page’s URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.

A practical example of this would be Twitter’s profile pages. If rendered by React Router, that route may look like this

<Route path='/:handle' component={Profile} />

Then the Profile component would be able to access the dynamic handle from props.match.params.handle.

class Profile extends React.Component {
  state = {
    user: null
  }
  componentDidMount () {
    const { handle } = this.props.match.params

    fetch(`https://api.twitter.com/user/${handle}`)
      .then((user) => {
        this.setState(() => ({ user }))
      })
  }
  render() {
    ...
  }
}

Let’s look at the example from the React Router docs now. First, we’ll need to import the components we’ll need and build a navbar. We’ll be navigating between the /netflix, /zillow-group, /yahoo, and /module-create paths.

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

class App extends React.Component {
  render() {
    return (
      <Router>
        <h2>Accounts</h2>
        <ul>
          <li><Link to="/netflix">Netflix</Link></li>
          <li><Link to="/zillow-group">Zillow Group</Link></li>
          <li><Link to="/yahoo">Yahoo</Link></li>
          <li><Link to="/modus-create">Modus Create</Link></li>
        </ul>
      </Router>
    )
  }
}

export default App

Each of those paths are going to render the same Child component which will just show the URL parameter’s value (which we’ll call id).

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

Now we have our navbar and the component to render, the only thing left to do is to render a Route with a URL paramter.

render() {
  return (
    <Router>
      <h2>Accounts</h2>
      <ul>
        <li><Link to="/netflix">Netflix</Link></li>
        <li><Link to="/zillow-group">Zillow Group</Link></li>
        <li><Link to="/yahoo">Yahoo</Link></li>
        <li><Link to="/modus-create">Modus Create</Link></li>
      </ul>

      <Route path="/:id" component={Child}/>
    </Router>
  )
}

And that’s it. Because we’re using URL parameters, we can have four different paths render the exact same component and that component will be passed the URL parameter (in this case id) as a prop.

Liked this post? Share it 🕺

This is part of our React Router v4 course. Check it out if you like this post.