onBlur prevents onClick to execute

Let's assume that you have the following component:

import React, { useState } from 'react'

const Field = () => {

    const [name, setName] = useState('erik')

    const handleClick = () => alert('Click')
    const handleBlur  = () => alert('Blur')
    const handleName  = e  => setName(e.target.value)

    return (
            <button onClick  = {handleClick}>Click me</button>
                onBlur   = {handleBlur}
                onChange = {handleName} 
                value    = {name}


export default Field

If you try to click the button while you are writing, it won't display the 'Click' alert, as onBlur prevents onClick to execute.

A solution could be to use onMouseDown instead of onClick. That works because the onMouseDown event has a higher priority than the onBlur event.


<button onMouseDown = {handleClick}>Click me</button>

Another solution colud be to delay the blur event a few ms.


<input onBlur = {() => setTimeout(handleBlur, 100)}>

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