-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Add React.createRef doc #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c09a284
ee78358
b049931
9bc1932
6627687
0e7243f
c07a6b0
7b02740
d7b34d4
8075ce2
96fe82c
96b10a7
962ef9a
4b939d2
04c7f16
b1adba0
9b869fa
5e0901d
3f304b9
f6e5d65
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,6 +11,8 @@ redirect_from: | |
permalink: docs/refs-and-the-dom.html | ||
--- | ||
|
||
Refs provide a way to access DOM nodes or React elements created in the render method. | ||
|
||
In the typical React dataflow, [props](/docs/components-and-props.html) are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch. | ||
|
||
### When to Use Refs | ||
|
@@ -29,32 +31,69 @@ For example, instead of exposing `open()` and `close()` methods on a `Dialog` co | |
|
||
Your first inclination may be to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. See the [Lifting State Up](/docs/lifting-state-up.html) guide for examples of this. | ||
|
||
### Adding a Ref to a DOM Element | ||
> Note | ||
> | ||
> The examples below have been updated to use the React.createRef() API introduced in React 16.3. If you are using an earlier release of React, we recommend using [#callback-refs](callback refs) instead. | ||
|
||
### Creating Refs | ||
|
||
Refs are created using `React.createRef()` and attached to React elements via the `ref` attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the the component. | ||
|
||
```javascript{4,7} | ||
class MyComponent extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
this.myRef = React.createRef(); | ||
} | ||
render() { | ||
return <div ref={this.myRef} />; | ||
} | ||
} | ||
``` | ||
|
||
### Accessing Refs | ||
|
||
When a ref is passed to an element in `render`, a reference to the node becomes accessible at the `value` attribute of the ref. | ||
|
||
React supports a special attribute that you can attach to any component. The `ref` attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted. | ||
```javascript | ||
const node = this.myRef.value | ||
``` | ||
|
||
The value of the ref differs depending on the type of the node: | ||
|
||
- When the `ref` attribute is used on an HTML element, the `ref` created in the constructor with `React.createRef()` receives the underlying DOM element as its `value` property. | ||
- When the `ref` attribute is used on a custom class component, the `ref` object receives the mounted instance of the component as its `value`. | ||
- **You may not use the `ref` attribute on functional components** because they don't have instances. | ||
|
||
The examples below demonstrate the differences. | ||
|
||
When the `ref` attribute is used on an HTML element, the `ref` callback receives the underlying DOM element as its argument. For example, this code uses the `ref` callback to store a reference to a DOM node: | ||
#### Adding a Ref to a DOM Element | ||
|
||
```javascript{8,9,19} | ||
This code uses a `ref` to store a reference to a DOM node: | ||
|
||
```javascript{5,12,22} | ||
class CustomTextInput extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
// create a ref to store the textInput DOM element | ||
this.textInput = React.createRef(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These changes break the line highlighting above
You'll want to update the line number offsets. Might also be a nice time to move these examples into the "examples" folder so Prettier can manage the formatting for us. (Totally optional though.) This would allow you to use the nicer "highlight-line" and "highlight-range" directives. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. 👍 |
||
this.focusTextInput = this.focusTextInput.bind(this); | ||
} | ||
|
||
focusTextInput() { | ||
// Explicitly focus the text input using the raw DOM API | ||
this.textInput.focus(); | ||
// Note: we're accessing "value" to get the DOM node | ||
this.textInput.value.focus(); | ||
} | ||
|
||
render() { | ||
// Use the `ref` callback to store a reference to the text input DOM | ||
// element in an instance field (for example, this.textInput). | ||
// tell React that we want the associate the <input> ref | ||
// with the `textInput` that we created in the constructor | ||
return ( | ||
<div> | ||
<input | ||
type="text" | ||
ref={(input) => { this.textInput = input; }} /> | ||
ref={this.textInput} /> | ||
<input | ||
type="button" | ||
value="Focus the text input" | ||
|
@@ -66,24 +105,26 @@ class CustomTextInput extends React.Component { | |
} | ||
``` | ||
|
||
React will call the `ref` callback with the DOM element when the component mounts, and call it with `null` when it unmounts. `ref` callbacks are invoked before `componentDidMount` or `componentDidUpdate` lifecycle hooks. | ||
|
||
Using the `ref` callback just to set a property on the class is a common pattern for accessing DOM elements. The preferred way is to set the property in the `ref` callback like in the above example. There is even a shorter way to write it: `ref={input => this.textInput = input}`. | ||
React will assign the `value` property with the DOM element when the component mounts, and assign it back to `null` when it unmounts. `ref` updates happen before `componentDidMount` or `componentDidUpdate` lifecycle hooks. | ||
|
||
### Adding a Ref to a Class Component | ||
#### Adding a Ref to a Class Component | ||
|
||
When the `ref` attribute is used on a custom component declared as a class, the `ref` callback receives the mounted instance of the component as its argument. For example, if we wanted to wrap the `CustomTextInput` above to simulate it being clicked immediately after mounting: | ||
If we wanted to wrap the `CustomTextInput` above to simulate it being clicked immediately after mounting, we could use a ref to get access to the custom input and call its `focusTextInput` method manually: | ||
|
||
```javascript{3,9} | ||
```javascript{4,8,13} | ||
class AutoFocusTextInput extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
this.textInput = React.createRef(); | ||
} | ||
|
||
componentDidMount() { | ||
this.textInput.focusTextInput(); | ||
this.textInput.value.focusTextInput(); | ||
} | ||
|
||
render() { | ||
return ( | ||
<CustomTextInput | ||
ref={(input) => { this.textInput = input; }} /> | ||
<CustomTextInput ref={this.textInput} /> | ||
); | ||
} | ||
} | ||
|
@@ -97,21 +138,24 @@ class CustomTextInput extends React.Component { | |
} | ||
``` | ||
|
||
### Refs and Functional Components | ||
#### Refs and Functional Components | ||
|
||
**You may not use the `ref` attribute on functional components** because they don't have instances: | ||
|
||
```javascript{1,7} | ||
```javascript{1,8,13} | ||
function MyFunctionalComponent() { | ||
return <input />; | ||
} | ||
|
||
class Parent extends React.Component { | ||
constructor(props) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Line highlights are off. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. 👍 |
||
super(props); | ||
this.textInput = React.createRef(); | ||
} | ||
render() { | ||
// This will *not* work! | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Unrelated to this diff: I wonder if we should highlight this (comment) line too? |
||
return ( | ||
<MyFunctionalComponent | ||
ref={(input) => { this.textInput = input; }} /> | ||
<MyFunctionalComponent ref={this.textInput} /> | ||
); | ||
} | ||
} | ||
|
@@ -123,25 +167,25 @@ You can, however, **use the `ref` attribute inside a functional component** as l | |
|
||
```javascript{2,3,6,13} | ||
function CustomTextInput(props) { | ||
// textInput must be declared here so the ref callback can refer to it | ||
let textInput = null; | ||
// textInput must be declared here so the ref can refer to it | ||
let textInput = React.createRef(); | ||
|
||
function handleClick() { | ||
textInput.focus(); | ||
textInput.value.focus(); | ||
} | ||
|
||
return ( | ||
<div> | ||
<input | ||
type="text" | ||
ref={(input) => { textInput = input; }} /> | ||
ref={textInput} /> | ||
<input | ||
type="button" | ||
value="Focus the text input" | ||
onClick={handleClick} | ||
/> | ||
</div> | ||
); | ||
); | ||
} | ||
``` | ||
|
||
|
@@ -151,11 +195,11 @@ In rare cases, you might want to have access to a child's DOM node from a parent | |
|
||
While you could [add a ref to the child component](#adding-a-ref-to-a-class-component), this is not an ideal solution, as you would only get a component instance rather than a DOM node. Additionally, this wouldn't work with functional components. | ||
|
||
Instead, in such cases we recommend exposing a special prop on the child. The child would take a function prop with an arbitrary name (e.g. `inputRef`) and attach it to the DOM node as a `ref` attribute. This lets the parent pass its ref callback to the child's DOM node through the component in the middle. | ||
Instead, in such cases we recommend exposing a special prop on the child. This prop can be named anything other than ref (e.g. inputRef). The child component can then forward the prop to the DOM node as a ref attribute. This lets the parent pass its ref to the child's DOM node through the component in the middle. | ||
|
||
This works both for classes and for functional components. | ||
|
||
```javascript{4,13} | ||
```javascript{4,12,16} | ||
function CustomTextInput(props) { | ||
return ( | ||
<div> | ||
|
@@ -165,25 +209,27 @@ function CustomTextInput(props) { | |
} | ||
|
||
class Parent extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
this.inputElement = React.createRef(); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Line highlights are off. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed 👍 |
||
render() { | ||
return ( | ||
<CustomTextInput | ||
inputRef={el => this.inputElement = el} | ||
/> | ||
<CustomTextInput inputRef={this.inputElement} /> | ||
); | ||
} | ||
} | ||
``` | ||
|
||
In the example above, `Parent` passes its ref callback as an `inputRef` prop to the `CustomTextInput`, and the `CustomTextInput` passes the same function as a special `ref` attribute to the `<input>`. As a result, `this.inputElement` in `Parent` will be set to the DOM node corresponding to the `<input>` element in the `CustomTextInput`. | ||
In the example above, `Parent` passes its class property `this.inputElement` as an `inputRef` prop to the `CustomTextInput`, and the `CustomTextInput` passes the same ref as a special `ref` attribute to the `<input>`. As a result, `this.inputElement.value` in `Parent` will be set to the DOM node corresponding to the `<input>` element in the `CustomTextInput`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: I think this example might read clearer if the parent class property was |
||
|
||
Note that the name of the `inputRef` prop in the above example has no special meaning, as it is a regular component prop. However, using the `ref` attribute on the `<input>` itself is important, as it tells React to attach a ref to its DOM node. | ||
|
||
This works even though `CustomTextInput` is a functional component. Unlike the special `ref` attribute which can [only be specified for DOM elements and for class components](#refs-and-functional-components), there are no restrictions on regular component props like `inputRef`. | ||
|
||
Another benefit of this pattern is that it works several components deep. For example, imagine `Parent` didn't need that DOM node, but a component that rendered `Parent` (let's call it `Grandparent`) needed access to it. Then we could let the `Grandparent` specify the `inputRef` prop to the `Parent`, and let `Parent` "forward" it to the `CustomTextInput`: | ||
|
||
```javascript{4,12,22} | ||
```javascript{4,12,20,24} | ||
function CustomTextInput(props) { | ||
return ( | ||
<div> | ||
|
@@ -200,26 +246,107 @@ function Parent(props) { | |
); | ||
} | ||
|
||
|
||
class Grandparent extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
this.inputElement = React.createRef(); | ||
} | ||
render() { | ||
return ( | ||
<Parent inputRef={this.inputElement} /> | ||
); | ||
} | ||
} | ||
``` | ||
|
||
Here, the ref `this.inputElement` is first specified by `Grandparent`. It is passed to the `Parent` as a regular prop called `inputRef`, and the `Parent` passes it to the `CustomTextInput` as a prop too. Finally, the `CustomTextInput` reads the `inputRef` prop and attaches the passed ref as a `ref` attribute to the `<input>`. As a result, `this.inputElement.value` in `Grandparent` will be set to the DOM node corresponding to the `<input>` element in the `CustomTextInput`. | ||
|
||
When possible, we advise against exposing DOM nodes, but it can be a useful escape hatch. Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use [`findDOMNode()`](/docs/react-dom.html#finddomnode), but it is discouraged. | ||
|
||
### Callback Refs | ||
|
||
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. | ||
|
||
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 = () => { | ||
// 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). | ||
return ( | ||
<Parent | ||
<div> | ||
<input | ||
type="text" | ||
ref={this.setTextInputRef} | ||
/> | ||
<input | ||
type="button" | ||
value="Focus the text input" | ||
onClick={this.focusTextInput} | ||
/> | ||
</div> | ||
); | ||
} | ||
} | ||
``` | ||
|
||
React will call the `ref` callback with the DOM element when the component mounts, and call it with `null` when it unmounts. `ref` callbacks are invoked before `componentDidMount` or `componentDidUpdate` lifecycle hooks. | ||
|
||
You can pass callback refs between components like you can with object refs that were created with `React.createRef()`. | ||
|
||
```javascript{4,13} | ||
function CustomTextInput(props) { | ||
return ( | ||
<div> | ||
<input ref={props.inputRef} /> | ||
</div> | ||
); | ||
} | ||
|
||
class Parent extends React.Component { | ||
render() { | ||
return ( | ||
<CustomTextInput | ||
inputRef={el => this.inputElement = el} | ||
/> | ||
); | ||
} | ||
} | ||
``` | ||
|
||
Here, the ref callback is first specified by `Grandparent`. It is passed to the `Parent` as a regular prop called `inputRef`, and the `Parent` passes it to the `CustomTextInput` as a prop too. Finally, the `CustomTextInput` reads the `inputRef` prop and attaches the passed function as a `ref` attribute to the `<input>`. As a result, `this.inputElement` in `Grandparent` will be set to the DOM node corresponding to the `<input>` element in the `CustomTextInput`. | ||
|
||
All things considered, we advise against exposing DOM nodes whenever possible, but this can be a useful escape hatch. Note that this approach requires you to add some code to the child component. If you have absolutely no control over the child component implementation, your last option is to use [`findDOMNode()`](/docs/react-dom.html#finddomnode), but it is discouraged. | ||
In the example above, `Parent` passes its ref callback as an `inputRef` prop to the `CustomTextInput`, and the `CustomTextInput` passes the same function as a special `ref` attribute to the `<input>`. As a result, `this.inputElement` in `Parent` will be set to the DOM node corresponding to the `<input>` element in the `CustomTextInput`. | ||
|
||
### Legacy API: String Refs | ||
|
||
If you worked with React before, you might be familiar with an older API where the `ref` attribute is a string, like `"textInput"`, and the DOM node is accessed as `this.refs.textInput`. We advise against it because string refs have [some issues](https://github.com/facebook/react/pull/8333#issuecomment-271648615), are considered legacy, and **are likely to be removed in one of the future releases**. If you're currently using `this.refs.textInput` to access refs, we recommend the callback pattern instead. | ||
If you worked with React before, you might be familiar with an older API where the `ref` attribute is a string, like `"textInput"`, and the DOM node is accessed as `this.refs.textInput`. We advise against it because string refs have [some issues](https://github.com/facebook/react/pull/8333#issuecomment-271648615), are considered legacy, and **are likely to be removed in one of the future releases**. | ||
|
||
> Note | ||
> | ||
> If you're currently using `this.refs.textInput` to access refs, we recommend the callback pattern instead. | ||
|
||
### Caveats | ||
### Caveats with callback refs | ||
|
||
If the `ref` callback is defined as an inline function, it will get called twice during updates, first with `null` and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the `ref` callback as a bound method on the class, but note that it shouldn't matter in most cases. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wording nit: We have a lot of sentences with both "ref" and "reference". It's fine, but I wonder if it might read better if we swapped "reference" with "pointer" in some of these places?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe... but pointer isn't particularly common terminology in JS-land so I'd worry it might confuse some people.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Terms like "pointer" and "reference" aren't just used in programming. I think they have broader meaning outside of programming that's relevant.
Maybe someone like @gaearon could weigh-in with an opinion about non-native English speakers and if there are concerns there though. I have no idea.