diff --git a/content/docs/refs-and-the-dom.md b/content/docs/refs-and-the-dom.md index 0fc033df0..d165c05a5 100644 --- a/content/docs/refs-and-the-dom.md +++ b/content/docs/refs-and-the-dom.md @@ -267,18 +267,25 @@ All things considered, we advise against exposing DOM nodes whenever possible, b React also supports another way to set refs called "callback refs", which give 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. + +The example below implements a common pattern: using the `ref` callback to store a reference to a DOM node in an instance property. ```javascript{6,17} class CustomTextInput extends React.Component { constructor(props) { super(props); + this.textInput = { value: null }; // initial placeholder for the ref 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 () { + if (this.textInput) this.focusTextInput() // autofocus the input on mount + } + 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 +293,7 @@ class CustomTextInput extends React.Component {