diff --git a/content/docs/reference-events.md b/content/docs/reference-events.md index 0cadd3728df..728716b10bd 100644 --- a/content/docs/reference-events.md +++ b/content/docs/reference-events.md @@ -167,10 +167,84 @@ These focus events work on all elements in the React DOM, not just form elements Properties: -```javascript +```js DOMEventTarget relatedTarget ``` +#### onFocus + +The `onFocus` event is called when the element (or some element inside of it) receives focus. For example, it's called when the user clicks on a text input. + +```javascript +function Example() { + return ( + { + console.log('Focused on input'); + }} + placeholder="onFocus is triggered when you click this input." + /> + ) +} +``` + +#### onBlur + +The `onBlur` event handler is called when focus has left the element (or left some element inside of it). For example, it's called when the user clicks outside of a focused text input. + +```javascript +function Example() { + return ( + { + console.log('Triggered because this input lost focus'); + }} + placeholder="onBlur is triggered when you click this input and then you click outside of it." + /> + ) +} +``` + +#### Detecting Focus Entering and Leaving + +You can use the `currentTarget` and `relatedTarget` to differentiate if the focusing or blurring events originated from _outside_ of the parent element. Here is a demo you can copy and paste that shows how to detect focusing a child, focusing the element itself, and focus entering or leaving the whole subtree. + +```javascript +function Example() { + return ( +
{ + if (e.currentTarget === e.target) { + console.log('focused self'); + } else { + console.log('focused child', e.target); + } + if (!e.currentTarget.contains(e.relatedTarget)) { + // Not triggered when swapping focus between children + console.log('focus entered self'); + } + }} + onBlur={(e) => { + if (e.currentTarget === e.target) { + console.log('unfocused self'); + } else { + console.log('unfocused child', e.target); + } + if (!e.currentTarget.contains(e.relatedTarget)) { + // Not triggered when swapping focus between children + console.log('focus left self'); + } + }} + > + + +
+ ); +} +``` + + * * * ### Form Events {#form-events}