Blog>
Snippets

Implementing Dynamic Masked Routes with Parameters

Detail the creation of dynamic routes that include parameters in the URL. This example explains how to mask routes with dynamic segments, capturing user ID or other parameters, while keeping the URL clean and readable.
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
Importing necessary components from react-router-dom to set up routing.
function UserDetails({ userId }) {
  // Component to display user details
  return <div>User ID: {userId}</div>;
}
Definition of a simple component to display user details, taking userId as a prop.
function App() {
  return (
    <Router>
      <Routes>
        <Route path='/user/:userId' element={({ match }) => <UserDetails userId={match.params.userId} />} />
      </Routes>
    </Router>
  );
}
Creating a dynamic route that masks the user ID parameter in the URL. The :userId part of the path is a placeholder for any user ID passed in the URL.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Rendering the App component into the root DOM node, initializing the single-page application.