Link and NavLink components in React-Router-Dom
The <Link> and <NavLink> are the components provided by react-router-dom to navigate around the react application. Generally, we use anchor tags for this purpose while navigating. Then what’s the difference? Let’s find out.
Anchor tags will reload the page and re-render all the components. While <Link> and <NavLink> will only re-render updated components matched with the URL path of the Route without reloading. It helps the Single-Page Applications to work faster while routing.
<Link> Component Props:
- to: String or object which specifies the pathname.
- replace: Replaces the pathname in the history stack with new.
- innerRef: Passes ref to the element rendered by the component.
<NavLink> Component Props:
- to, replace, innerRef same as the Link Component.
- className: Specifies the CSS class name you want to apply to the element when active.
- isActive: Returns boolean value whether the link is active or not.
- style: To apply inline CSS.
- end: Match the pathname precisely with the URL.
A <NavLink> is a special kind of <Link> that knows whether or not it is “active”. Now, let’s understand this with the help of an example.
Creating React Application And Installing Module:
Step 1: Create a new react application by the following command using terminal:
npx create-react-app <project_name>
Step 2: Go to the project folder by the following command:
Step 3: Install dependency react-router-dom using the following command:
npm install react-router-dom
Note: To check whether the dependency has been installed or not , go to package.json and checkout in the dependencies.
Step 4: Create a new folder named components in the src folder and add Home.js, About.js and Contact.js files to it.
Project Structure: The folder structure will look like the following:
Example: This example will demonstrate the use of Link and NavLink components in React-Router-Dom
Step to Run Application: Run the application using the following command from the root directory of the project: