How to use React Router with an optional path parameter

How to use React Router with an optional path parameter image

In this post we cover how to use React Router with an optional path parameter.

To use React Router with an optional path parameter, all you need to do is to append the path parameter with a ? question mark character, like so:

1<BrowserRouter>
2  <Switch>
3    <Route
4      path="/hello-world/:name?"
5      component={HelloWorldComponent}
6    />
7  </Switch>
8</BrowserRouter>

Another option is to use URL get parameters instead which gives a little more versatility and is natively supported in JavaScript.

To do the same as above with a GET parameter, it can be done like so:

Firstly, we would define the React Router path without the optional parameter like so:

1<BrowserRouter>
2  <Switch>
3    <Route
4      path="/hello-world/"
5      component={HelloWorldComponent}
6    />
7  </Switch>
8</BrowserRouter>

Secondly, within the component, (or a helper could be extracted) you would need to get the parameter from the URL like so:

1export default function HelloWorldComponent({ location }) {
2  const name = new URLSearchParams(location.search).get("name");
3  return (
4    <p>Hello, {name || "World"}!</p>
5  );
6}

In summary, you can either append your React Router path with a ? question mark character, or you can make use of URL GET parameters.

React Router

React Router is a client side router library built for use in React that helps with navigation in SPAs (Single Page Applications).

React

React or ReactJs is a library used for developing frontend applications. Its main concepts are based around state, props, and renders.

When a state variable or prop gets updated or changed, they trigger a render.

When a render happens the appropriate parts of the application essentially get re-built using the new values to provide a new UI to the user.

It is worth noting that a prop that causes a render is just a state variable that gets passed into another component.

JavaScript

JavaScript is a programming language that is primarily used to help build frontend applications.

It has many uses, such as making network requests, making dynamic or interactive pages, creating business logic and more.

Client Side Router

A client side router is a method of navigating and managing an applications routes and URL's from the frontend of an application.

It allows you to write a full application that can use various routes and URLS without ever leaving the page you are on.

This can be a useful technique to avoid loading in new static content by loading it in at the start or lazily rather than requesting the new resources by navigating to a new URL.

One important thing to remember about client side routers is that they do not handle "real" routing with status codes and so on by themselves.

Further resources

Related topics

How to pass a React component as a prop in TypeScriptWhat is Formik touched?How to use Apollo useQuery with multiple queriesHow to use css variables with ReactHow to use window.addEventListener with react hooksHow to use setState from within useEffectHow to continue in a JavaScript forEach loopHow to redirect in ReactJSHow to compare two dates in JavaScriptHow to use apollo client without hooks (useQuery, and useMutation)How to make a loop wait in JavaScriptHow to get postcodes from Google Places and Google Maps with JavaScriptHow to use useContext in functional componentsHow to calculate the number of days between two dates in JavaScript​​React.memo vs useMemoHow to make and use a Google autocomplete react hookHow to wait for all promises to resolve in JavaScriptHow to pass props to children in ReactHow to trim and remove leading zeros in JavaScriptHow to use dangerouslySetInnerHTML in ReactIs JavaScript forEach async?How to get the index in a forEach loop in JavaScriptHow to sort an array of objects by property value in JavaScriptHow to get the JavaScript forEach key value pairs from an objectHow to set the selected option on a select element with React and JSXHow to get the last segment of a URL in JavaScriptHow to split an array in two in JavaScriptHow to get the selected value in dropdown list using JavaScriptHow to test custom react hooksHow to rename a destructured variable in JavaScriptReact.Fragment vs divfindIndex vs indexOf in JavaScriptHow to sort an array by date in JavaScriptWhat is the difference between useMemo and useCallback?How to break a JavaScript forEach loopWhen to use useImperativeHandleHow to get yesterdays date in JavaScriptHow to initialize an array with values in JavaScriptHow to import and export a module on the same line in JavaScriptHow to get the month name in JavaScriptNullish Coalescing vs OR - JavaScript operators (?? vs ||)What are the differences between React.Fragment vs <>What is hydration in React based applications?What do multiple arrow functions mean in JavaScript?What are Expo modules in React NativeHow to programmatically navigate using React Router

Save code?

How to use React Router with an optional path parameter code example image

© 2024 MWXYZ