Placing a div inside of a Link to simulate the button behaviour

HTML5 specification doesn't allow to place buttons inside anchors.

Thus, we can't place interactive content descendants (e.g. buttons), <a></a> element descendants, or descendants with the tabindex attribute specified.

Instead of using a button, we can wrap a link to a div and trigger a function on click:

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

const CustomAnchor = () => {
    const doSomething = (e) => {
        alert('Clicked on div.');
        <Link to = '/'>
            <div onClick = {doSomething}>Do something on click</div>

export default CustomAnchor;

Notice how we need to prevent the default event to trigger to stop the redirection.

Now, if we click on 'Hello', we'll be redirected to the home. If we click on 'Do something on click', an alert will display, and we won't be redirected.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.