Navigating between pages using Link and NavLink components in React
Navigating between pages using Link and NavLink components
50
React is a popular JavaScript library used for building dynamic user interfaces for web applications. When it comes to creating a multi-page application, we need to be able to navigate users to different pages within the application. React provides two components for accomplishing this task; Link
and NavLink
.
Link
component is used to navigate between different pages within the application. It is part of the react-router-dom
library which provides powerful routing capabilities to React applications.
The syntax for using the Link
component is as follows:
import { Link } from 'react-router-dom'; <Link to='/about'>About</Link>
In the above code, we are importing the Link
component from react-router-dom
library and using it to create a hyperlink which navigates users to /about
page when clicked.
NavLink
is a similar component to Link
, but with added styling capabilities. It allows you to apply custom styles to the active NavLink
which makes it easier for users to understand where they are in the application.
The syntax for using the NavLink
component is as follows:
import { NavLink } from 'react-router-dom'; <NavLink to='/about' activeClassName='active'>About</NavLink>
In the above code, we are importing NavLink
component from react-router-dom
library and using it to create a hyperlink like Link
. The activeClassName
is a prop that can be used to apply custom styling to the active NavLink
element.
By using the Link
and NavLink
components in combination with the react-router-dom
library, we can create a seamless multi-page application with easy navigation controls.
March 25, 2023