How to detect route changes in navlink ReactJS
Introduction
Imagine being in a maze, where the path you're taking changes constantly and you need to keep track of where you've been. It can be a bit challenging, right? Well, our web applications can be like that maze. When we navigate through different components of our application, we are essentially changing routes. In this blog post, we are going to explore how to detect these route changes using NavLink in ReactJS.
What is ReactJS?
Before we dive into the deep end, let's understand what ReactJS is. ReactJS is a JavaScript library built by Facebook. It's like a set of Lego blocks which we can use to build user interfaces (UI). A UI is what you see on your screen when you're using an application, like buttons, images, and text. Instead of creating the whole UI as one big chunk, ReactJS allows us to break it down into smaller, reusable pieces known as components.
What is Routing?
In the context of web development, routing refers to the process of setting up paths for different pages or components in a web application. It's like the system of roads in a city. Each road (route) leads to a different destination (component). In our maze analogy, each path you take is a route that leads to different parts of the maze.
ReactJS itself doesn't come with built-in routing, but there's a library we can use for this purpose: React Router. It provides a set of tools that helps us define these routes in our ReactJS application.
Using NavLink for Routing
One of these tools provided by React Router is NavLink. NavLink is a special type of component that we can use to create links in our application. It's like the signpost in our maze. When you click on a NavLink, you are taken to the corresponding route.
Now, let's see how we can use NavLink in our code.
import { NavLink } from 'react-router-dom';
<NavLink to="/home" exact activeStyle={{ color: 'green' }}>Home</NavLink>
In the above snippet, we first import NavLink from 'react-router-dom'. Then, we use it to define a link. The to
prop specifies the route that this link will lead to when clicked. The exact
prop ensures that this route is only active when the path is exactly '/home'. The activeStyle
prop specifies the style that will be applied to this link when the route is active.
Detecting Route Changes
Now that we know how to set up routes using NavLink, let's move on to the main topic: detecting route changes.
Using the useHistory
Hook
One way to detect route changes is by using the useHistory
hook from 'react-router-dom'. This hook gives us access to the history object which keeps track of the current location (route) and past locations.
Here is how we can use it:
import { useHistory } from 'react-router-dom';
function ExampleComponent() {
const history = useHistory();
history.listen((location, action) => {
console.log(`The current route is ${location.pathname}`);
});
return <div>Example Component</div>;
}
In this code snippet, we first import the useHistory
hook. Inside our ExampleComponent
, we call this hook and store the returned history object in a variable. We then use the listen
method of the history object to listen for route changes. Every time the route changes, our callback function is called with the new location and the action that caused the change. We log the new route to the console.
Using the useEffect
Hook
Another way to detect route changes is by using the useEffect
hook together with the useLocation
hook. The useEffect
hook lets us perform side effects in our components, and the useLocation
hook lets us access the current location object.
Here's how we can use them:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function ExampleComponent() {
const location = useLocation();
useEffect(() => {
console.log(`The current route is ${location.pathname}`);
}, [location]);
return <div>Example Component</div>;
}
In this code snippet, we first import the useEffect
and useLocation
hooks. Inside our ExampleComponent
, we call the useLocation
hook to get the current location object. We then use the useEffect
hook to set up a side effect that logs the current route to the console. We pass the location object as a dependency to useEffect
, so our side effect runs every time the location object changes, i.e., every time the route changes.
Conclusion
In this blog post, we've navigated through the maze of route detection in ReactJS using NavLink. We've seen how to set up routes using NavLink and how to detect route changes using the useHistory
and useEffect
hooks. Remember, in the maze of web development, every turn you take is a learning opportunity. Happy coding!