DEV Community

Cover image for Link, NavLink or useHistory?
Aastha Pandey
Aastha Pandey

Posted on • Updated on

Link, NavLink or useHistory?

I used to use NavLink instead of a button more often because I didn't know how to link that button to a specific URL while using react-router, useHistory hook provided by react-router can be used with a button.

import { useHistory } from 'react-router-dom'

const history = useHistory();
const handleLogin = () => {
history.push('/homepage')
}
<button onClick = {handleLogin}>Login</button>

Enter fullscreen mode Exit fullscreen mode

NavLink should be used with some kind of navigation bar as it will be helpful in showing which tab is active and at the same time will be able to take to some other linked URL.
And also if the navigation bar is visible to the user while navigating to other pages then NavLink is a better choice.

import { NavLink } from 'react-router-dom'

<NavLink to = '/home' style = {{background: 'green'}} activeStyle = {{background: 'red'}}>Home</NavLink>
<NavLink to = '/about' style = {{background: 'green'}} activeStyle = {{background: 'red'}}>About</NavLink>
<NavLink to = '/dashboard' style = {{background: 'green'}} activeStyle = {{background: 'red'}}>Dashboard</NavLink>

Enter fullscreen mode Exit fullscreen mode

Link too should be used with some kind of navigation bar but it will not be helpful in showing which tab is active without some extra css effort but the sole purpose of linking it to some URL will be served.
And also if the navigation bar is not visible to the user while navigating to other pages then Link is a better choice.

import { Link } from 'react-router-dom'

<Link to = '/home' style = {{background: 'green'}>Home</Link>
<Link to = '/about' style = {{background: 'green'}} >About</Link>
<Link to = '/dashboard' style = {{background: 'green'}} >Dashboard</Link>

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
devcamila profile image
Camila Lacerda

Thank you!! Great content 👏😍