diff --git a/content/docs/refs-and-the-dom.md b/content/docs/refs-and-the-dom.md index 0fc033df..24aa8095 100644 --- a/content/docs/refs-and-the-dom.md +++ b/content/docs/refs-and-the-dom.md @@ -265,20 +265,34 @@ All things considered, we advise against exposing DOM nodes whenever possible, b ### Callback Refs -React also supports another way to set refs called "callback refs", which give more fine-grain control over when refs are set and unset. +React also supports another way to set refs called "callback refs", which gives more fine-grain control over when refs are set and unset. -Instead of passing a `ref` attribute created by `createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. This example uses the `ref` callback to store a reference to a DOM node: +Instead of passing a `ref` attribute created by `createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. -```javascript{6,17} +The example below implements a common pattern: using the `ref` callback to store a reference to a DOM node in an instance property. + +```javascript{5,7-9,11-14,19,29,34} class CustomTextInput extends React.Component { constructor(props) { super(props); + + this.textInput = { value: null }; // initial placeholder for the ref + + this.setTextInputRef = element => { + this.textInput.value = element + }; + this.focusTextInput = () => { - // Explicitly focus the text input using the raw DOM API - this.textInput.focus(); + // Focus the text input using the raw DOM API + this.textInput.value.focus(); }; } + componentDidMount () { + // autofocus the input on mount + if (this.textInput.value) this.focusTextInput() + } + render() { // Use the `ref` callback to store a reference to the text input DOM // element in an instance field (for example, this.textInput). @@ -286,7 +300,8 @@ class CustomTextInput extends React.Component {
{ this.textInput = input; }} /> + ref={this.setTextInputRef} + /> this.textInput = input}`. - You can pass callback refs between components like you can with object refs that were created with `React.createRef()`. ```javascript{4,13}