From 8075ce2db759a41af4d86a4dc96eac9fecc60a0f Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 3 Mar 2018 18:53:16 -0800 Subject: [PATCH] Make the callback example more similar to the new API --- content/docs/refs-and-the-dom.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) 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 {
{ this.textInput = input; }} /> + ref={element => this.textInput.value = element} /> 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}