React JS Tutorial - Route Parameters

In this tutorial, we will learn about Route Parameters. Route parameters are parameters whose values are set dynamically in a page's URL, allowing a route to render the same component while passing that component the dynamic portion of the URL.

This enables the component to change its data based on the parameter. We can also pass a parameter with the route. React provides two ways of capturing the passed parameter: Required Parameter and Optional Parameter.

Required Parameter

Let's start with the Required Parameter. Before passing the parameter, create a new component, for example, `User.js`. Open this component and write the following code:


import React, { Component } from 'react'

class User extends Component {
state = {
name:null
}
componentDidMount(){
let name = this.props.match.params.name;
}

render() {
return (
<div>
<h3>{this.state.name}</h3>
</div>
)
}
}

export default User;

Next, add this component to the `App.js` file. Open `App.js` and import the `User` component.


import User from './components/User';

Create a route for the `User` component.


<BrowserRouter>
<Switch>
<Route exact path='/user/:name' component={User} />
</Switch>
</BrowserRouter>

Let's test it. In the browser, go to the URL `localhost:3000/user/Jeniffer`. You should see the name "Jeniffer" inside the `User` component.

If you change the name in the URL, for example, to `localhost:3000/user/John`, you should see the name "John" displayed. However, if you remove the parameter from the URL, it will throw an error. This means that a required parameter must be passed; otherwise, it will result in an error.

Optional Parameter

Now, let's see how to make a parameter optional. To do this, simply add parentheses to the route, like this:


<BrowserRouter>
<Switch>
<Route exact path='/user(/:name)' component={User} />
</Switch>
</BrowserRouter>

This makes the parameter optional. Let's test it. Switch to the browser and add a parameter to the URL. You should see the parameter value displayed. If you remove the name from the URL, it should still work without throwing an error.

In this way, you can add required or optional parameters to your React Router routes.