CodeNewbie Community 🌱

Irakli Tchigladze
Irakli Tchigladze

Posted on • Updated on

Add onClick event handler to Link component in React

React is the most popular library for building UIs, but it lack essential features to build a fully functional web application. Routing is one of these crucial features missing from React. Fortunately, React has a community of developers who have created react-router, a great library to add navigation features in React.

Why do we need react-router?

React-router provides many essential components for building apps in React. <Router>, <Route>, <Link> just to name a few. In this article, we’ll focus on the last custom component on this list. Specifically, I want to explore how to set onClick event handler on <Link> component in React.

You might think that because Link is a custom component and not a React element, you can not set event handlers on it. That’s not true. Some components might not support event handlers, but <Link> does. It works similar to a normal anchor tag in HTML. The only difference is that clicking a <Link> custom component does not reload the page.

Set onClick on <Link>

Adding an onClick event handler to <Link> can have a number of consequences. First, and most important is that whenever users click the text, link will perform an additional action. First, React will handle the click event. Only then user will be taken to the URL specified in the to prop of the <Link>. Sometimes this isn’t what you want. Event handler can interfere with the main functionality – taking users to a different URL. For this reason, many developers come up with different ways to achieve the result of setting onClick on <Link> in React.

Instead of setting onClick directly on the Link custom component, you can perform that action in a side effect of the component(s) that are going to render when user reaches the destination. For example, if your link takes users to the /dashboard path, and that URL renders Dashboard component, you don’t really need to do something on the <Link> custom component. Instead, you can use the useEffect() hook in the Dashboard component to perform a side action.

Alternatives

Another option is to not use <Link> at all and instead use a normal button or a <span> element. Obviously, clicking these elements won’t automatically redirect user to a specific URL. However, you can use useNavigate() hook to programmatically take users to a different page. In the same event handler, you can also perform whatever action you had in mind. You can even make them look like a link, even if it’s only a button. SimpleFrontEnd has a great article with many examples on how to set onClick on <Link> components in React. It also explains why it may be a better idea to take the alternative approach.

Top comments (0)