The article introduces the concept of passing parameters to routes in React, which is crucial for creating dynamic and personalized user experiences. Using React Router, particularly React Router DOM, developers can define multiple routes and pass data such as user IDs or objects between components.
Welcome to the exciting world of React! If you've dabbled with this awesome library, you'll know that React has fundamentally transformed how we think about front-end development. But what happens when we need to pass specific data, say a user ID or other unique identifiers, from one component to another or from one screen to another?
This is where the concept of "passing parameters to routes" comes into play. In essence, passing parameters to routes allows us to create more dynamic, personalized experiences for our users.
The React Router module is one of the essential tools provided by React to manage navigation in your application. React Router, particularly React Router Dom, helps us define multiple routes for our application which aligns well with the component structure of React, thus creating a single page application with various views.
A crucial aspect of react-router is that it allows each React component to be associated with a particular route.
Passing parameters to routes in a React router enables components to access the parameters in a route's path. These parameters can be anything from a user object to a simple string or number, which can be very helpful when, for example, you want to pass data related to a specific user from one component to another.
It supports the idea of creating reusable and interactive components. Consider, that you need to pass the 'user object' and other parameters to different routes, allowing components associated with these routes to receive this 'user object' and render relevant user data. It can be achieved using the 'props object' or the 'useParams hook' provided by React Router Dom.
In React, props is a special keyword that stands for properties. It's an object passed to a component from its parent. This object allows us to pass data from the parent component to its child. Data passed using props can be any JavaScript object, function, or element.
Props in React facilitate the flow of data from parent components to child ones. This feature is particularly useful when you want to pass some custom data to the child component.
Here's a simple illustration of how we can pass data using props.
1 function Welcome(props) { 2 return <h1>Welcome, {props.name}!</h1>; 3 } 4 5 function App() { 6 return ( 7 <div className="App"> 8 <Welcome name="John" /> 9 </div> 10 ); 11 } 12
In the code above, we're passing the prop name from the App parent component to the Welcome child component.
One important thing to note about React components is that they should never modify their own props - they are read-only. Think of props in React as being similar to function arguments in JavaScript functions. Just like function arguments are treated as constants within the function, props in a component should be treated as unmodifiable ('read only') constants.
Furthermore, props can be passed to any component. For instance, if you have a component <ComponentA />
and you want to pass a user object as prop to it, you would do the following <ComponentA user={user} />
.
Passing a user object as a prop to a component is also straightforward. If you have a user object and you want to pass it to ComponentB from ComponentA, you can do something as shown below:
1 const userObj = { 2 name: 'Alex', 3 age: 25, 4 }; 5 6 function ComponentB(props) { 7 return ( 8 <div> 9 <h1>{props.user.name}</h1> 10 <p>Age: {props.user.age}</p> 11 </div> 12 ); 13 } 14 15 function ComponentA() { 16 return ( 17 <div className="App"> 18 <ComponentB user={userObj} /> 19 </div> 20 ); 21 } 22
The example above demonstrates how we can pass a user object to a React component, and how that object can be accessed within the component to render specific data.
Parameters, often referred to as params, are dynamic parts of the URL that can change and are set to a specific value when a particular route is matched. In React Router, parameters can be used to capture values from the URL, which can then be used to further personalize or specify what to render in a particular view. By passing parameters, we're making routes dynamic, allowing us to reuse the same component for different data based on the parameter value.
React Router DOM is a dynamic routing library built on top of the React Router library, which is made to work in a browser environment. This library allows your app to have multiple pages or views corresponding to various routes in the context of Single Page Applications (SPA). Hence, it's an essential tool for defining and managing routes in your React application.
Every route in the React Router is associated with a path. This path is a string or a regular expression, which React Router matches with the current URL. If the current URL matches the path of a route, the associated component or render prop function of that route gets rendered. The 'Route path' is where we can specify parameters that we want to pass to our components.
When defined in a route, parameters allow React Router to understand which part of the URL should be captured as a dynamic argument. These parameters can then be accessed in the routed components using the props passed by React Router. This way, parameters help in creating dynamic and personalized routes in a React application.
For example, if you have a user component that takes a user ID as a parameter, you can define the route path as "/user/:userId". Here ":userId" is a parameter, and its value can be accessed in the matched component as a prop - props.match.params.userId. This mechanism enables the creation of a detail view for each user in the application using the same User component.
1 import { Route } from 'react-router-dom'; 2 3 function UserDetail(props) { 4 return <div>User ID: {props.match.params.userId}</div>; 5 } 6 7 function App() { 8 return ( 9 <div className="App"> 10 <Route path="/user/:userId" component={UserDetail} /> 11 </div> 12 ); 13 } 14
In the code example above, the UserDetail component can access the userId prop and display a personalized view for each user.
Let's look at an example of how we can pass params in a React application using React Router Dom. Consider a scenario where we are developing a blog website, and we want to render different blog posts dynamically based on their IDs.
For this purpose, we can create a BlogPost component. Here's an example:
In the example, we have a BlogPost component that fetches the postId from the URL and renders it. Each link in the App component directs to a different blog post.
Passing data between screen components can be done using React Router as well. Here's how you can pass data from one screen component to another:
1 2 import { Route, Link } from 'react-router-dom'; 3 4 function Profile({ location }) { 5 const user = location.state.user; 6 return <h2>Welcome {user.name}</h2>; 7 } 8 9 function Home() { 10 const user = { name: 'John' }; 11 12 return ( 13 <div> 14 <h1>Home</h1> 15 <Link to={{ pathname: '/profile', state: { user } }}>Go to profile</Link> 16 </div> 17 ); 18 } 19 20 function App() { 21 return ( 22 <div className="App"> 23 <Route path="/" exact component={Home} /> 24 <Route path="/profile" component={Profile} /> 25 </div> 26 ); 27 } 28 29
In this sample, the Home component includes a Link to the Profile component and passes the user object in the state of the to prop.
We can set params in our route by signifying them in the path. We've seen this in the BlogPost example above where we've set a dynamic path: /post/:postId. After setting the path this way, we can navigate to the route by setting the path in the Link or NavLink components from react-router-dom.
React Router provides a hook called useParams() that we can use to access the match params of the current route. This hook makes it easy to extract params from the URL.
Here's an example:
1 import { Route, Link, useParams } from 'react-router-dom'; 2 3 function BlogPost() { 4 let { postId } = useParams(); 5 return <div>Post ID: {postId}</div>; 6 } 7 8 function App() { 9 return ( 10 <div className="App"> 11 <Link to='/post/1'>Post 1</Link> 12 <Link to='/post/2'>Post 2</Link> 13 <Link to='/post/3'>Post 3</Link> 14 <Route path="/post/:postId" component={BlogPost} /> 15 </div> 16 ); 17 } 18 19
In this example, the BlogPost component uses the useParams() hook to extract the postId from the URL.
Integrating APIs with React Router allows us to fetch data dynamically based on the route parameters. This can be extremely useful in scenarios where we want to display dynamic content based on the current route. Here's a simple step-by-step guide:
Let's consider an example where we are using a public API to fetch user data in a UserProfile component based on the 'userId' route parameter:
1 import { Route } from 'react-router-dom'; 2 import { useEffect, useState } from 'react'; 3 import axios from 'axios'; 4 5 function UserProfile(props) { 6 const [user, setUser] = useState(null); 7 const userId = props.match.params.userId; 8 9 useEffect(() => { 10 axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`) 11 .then(response => { 12 setUser(response.data); 13 }); 14 }, [userId]); 15 16 return user ? ( 17 <div>{user.name}</div> 18 ) : ( 19 <div>Loading...</div> 20 ); 21 } 22 23 function App() { 24 return ( 25 <div className="App"> 26 <Route path="/user/:userId" component={UserProfile} /> 27 </div> 28 ); 29 } 30
In this example, we are fetching data from a JSONPlaceholder API when the UserProfile component mounts.
The concept of passing parameters to routes in React paves the way for creating dynamic web applications. It not only forms the basis of how we fetch and display data dynamically based on user actions or interface states but also further reinforces the philosophy of component reuse. Custom spectral components, for instance, a product detail page in an e-commerce app, can be made significantly more dynamic by passing parameters to routes.
React Router further extends the paradigm of components and routing. It links UI components with URL changes, often triggered by user navigations. It allows devs to pass parameters to routes, further substantiating the dynamic link of components and URLs.
This brings us to the end of a comprehensive exploration of how to pass parameters to routes in React using React Router. Mastering parameter passing in React unlocks dynamic app possibilities, but building truly impactful experiences needs more.
Enter DhiWise React Builder!
Design stunning UIs visually, generate production-ready code, integrate data effortlessly, deploy with a click, and collaborate seamlessly. DhiWise empowers you to move beyond parameters and build dynamic, data-driven React apps that stand out. Dive in and experience the difference!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.