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:

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

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

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.