Sometimes, we want to get the onBlur method fire only when the focus gets out of an element with React.
In this article, we’ll look at how to get the onBlur method fire only when the focus gets out of an element with React.
How to get the onBlur method fire only when the focus gets out of an element with React?
To get the onBlur method fire only when the focus gets out of an element with React, we can check if the blur event is emitted by an element outside the given element with the e.currentTarget.contains
method.
For instance, we write:
import React from "react";
export default function App() {
const onBlur = (e) => {
if (!e.currentTarget.contains(e.relatedTarget)) {
console.log("blur event");
}
};
return (
<div>
<h1>Table</h1>
<table onBlur={onBlur}>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</tbody>
</table>
</div>
);
}
We define the onBlur
function that checks if the e.relatedTarget
is inside the e.currentTarget
with contains
.
e.currentTarget
is the element being blurred.
And e.relatedTarget
is the element that received the focus.
Therefore, if the element that received the focus isn’t the element inside the table, then we know the focus is outside the table.
As a result, only when we focus away from the last input then the onBlur
function will be run.
Conclusion
To get the onBlur method fire only when the focus gets out of an element with React, we can check if the blur event is emitted by an element outside the given element with the e.currentTarget.contains
method.