React Router V6 provides lots of features that make development easier. In this post, I will discuss about the React useNavigate hook. This hook is used to redirect from one component to another or one link to another. The exciting part is, that you can pass values by redirecting from component to component. The value can be a string or in the form of an array or object. It totally depends on your need. It just gives a way to redirect along with some data. Also, we will see useLocation hook for capturing the props. Let’s take a look by having a demo app in React js.
At least, we will have two components in this app demo. From the first component, we will redirect to the second one. But, we will use the React useNavigate hook. Also, we will pass some props with this navigation.
We have the second component. Here, we will capture the props then we will be redirected back to the first component.
Prerequisites
Before reading this post, I hope you are having a good understanding of React and React Router DOM. This post will be totally dependent on these.
Form Handling in React JS Using React Hook Form Library
Create React App
For creating an app in React js, you can open the terminal and hit the below command.
npx create-react-app router-app
Once the app is created, let’s open it in the editor and run it.
npm start
If your app runs in the browser then you are good to go in the next step.
How to Use useEffect Hook in React Functional Component
Install React Router DOM in React Js
In the next step, you will need to install an additional library for the routing. This library provides the useNavigate hook. Using this hook, we will be able to redirect from one component to another with data.
npm i react-router-dom
I am using npm to install this library. You may use yarn as well. Once, it is installed, you can check the package.json file for the details.
So, here, we have the React Router V6. If you have the earlier version, it won’t support the useNavigate hook and other features that we are going to cover here.
Now, let’s navigate to the app folder. We will create a few components here.
Create Components in React Js
For passing props among components using react useNavigate hook, I will create two components for now. It will enough for the demonstration purpose.
So, let’s create these two components in the app.
- Home.jsx
- About.jsx
Once, you are done with the components, let’s add the below snippets. Firstly, start with the Home component.
import React from "react";
import { useNavigate } from "react-router-dom";
export const Home = () => {
const navigate = useNavigate();
const redirectToAbout = () => {
navigate("/about");
};
return (
<div className="container text-center py-5">
<h3> Home component </h3>
<button
type="button"
className="btn btn-primary"
onClick={redirectToAbout}
>
Redirect to About
</button>
</div>
);
};
Similarly, add the below snippet in the About component.
import React from "react";
import { useNavigate } from "react-router-dom";
export const About = () => {
const navigate = useNavigate();
const redirectToHome = () => {
navigate("/");
};
return (
<div className="container text-center py-5">
<h3> About Us Component</h3>
<button
type="button"
className="btn btn-primary"
onClick={redirectToHome}
>
Redirect to Home
</button>
</div>
);
};
Now, for rendering these two components, let’s add routes in the App component.
How to Create Todo App in React JS Using Redux
Add Routes in React Js
For adding the routes, you can add them in the App component.
import React from 'react';
import { Home } from './components/Home';
import { About } from './components/About';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
export const App = () => {
return (
<div className="App">
<Router>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
</Routes>
</Router>
</div>
);
}
The App component is rendered in the index.js file of the application.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import { App } from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Now, let’s check the result. Initially, you will have the Home component having a button.
When you click on the Redirect button, it will open the About component.
This is simple navigation between these two components.
Now, let’s see how to pass props here with navigation.
Pass Props/Data in React useNavigate Hook
The React useNavigate hooks accept parameters as props in the state object. That means you can pass N number of props inside the state object. The props can be of any data type. So, the syntax is shown below.
const navigate = useNavigate();
navigate('routeName', {
state: {
props
}
});
Now, let’s implement this in our app. Add the below snippet in the Home component.
import React from "react";
import { useNavigate } from "react-router-dom";
export const Home = () => {
const navigate = useNavigate();
// redirecting to about component
const redirectToAbout = () => {
navigate("/about", {
state: {
name: 'Programming Fields',
message: 'Message from home component',
},
});
};
return (
<div className="container text-center py-5">
<h3> Home component </h3>
<button
type="button"
className="btn btn-primary"
onClick={redirectToAbout}
>
Redirect to About
</button>
</div>
);
};
In the above snippet, I have passed the state object in the second parameter of the navigate() function.
Now, we have to receive the state props in the target component.
Get State Props in Component Using useLocation Hook
To get the state props, come to the target component where you want to get the data. In this case, we will get the data into the About component.
For getting the state props data, we will use another hook (useLocation) provided by the React Router DOM.
So, firstly, you will have to import this hook at the top just like other imports.
import { useLocation } from 'react-router-dom'
Then inside the component, you have to create its object.
const location = useLocation();
Let’s apply this to our component.
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
export const About = () => {
const navigate = useNavigate();
const location = useLocation();
console.log('location', location)
const redirectToHome = () => {
navigate("/");
};
return (
<div className="container text-center py-5">
<h3> About Us Component</h3>
<button
type="button"
className="btn btn-primary"
onClick={redirectToHome}
>
Redirect to Home
</button>
</div>
);
};
Here, we have used the useLocation hook for capturing the URL params or any other props.
I have logged the incoming props data in the console. Let’s see what we are getting after redirecting to the About component.
So, in the above response, you can see the incoming props are inside the state object. Now, we can print these values in the component itself.
This is the final block snippet of the About component.
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
export const About = () => {
const navigate = useNavigate();
const location = useLocation();
const redirectToHome = () => {
navigate("/");
};
return (
<div className="container text-center py-5">
<h3> About Us Component </h3>
<h5> {location.state.name} </h5>
<p> {location.state.message} </p>
<button
type="button"
className="btn btn-primary"
onClick={redirectToHome}
>
Redirect to Home
</button>
</div>
);
};
Refresh and check the result. Here, we captured the props on the UI.
That’s it for this post. I hope you will find helpful to this post. If you have any doubts then you can raise your questions in the comment section. I will love to resolve your queries. In the next post, we will dig more into the useLocation hook.
Leave a Reply