Movatterモバイル変換


[0]ホーム

URL:


We want to hear from you!Take our 2021 Community Survey!
This site is no longer updated.Go to react.dev

Refs and the DOM

These docs are old and won’t be updated. Go toreact.dev for the new React docs.

These new documentation pages teach modern React and include live examples:

Refs provide a way to access DOM nodes or React elements created in the render method.

In the typical React dataflow,props 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

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Avoid using refs for anything that can be done declaratively.

For example, instead of exposingopen() andclose() methods on aDialog component, pass anisOpen prop to it.

Don’t Overuse Refs

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 theLifting State Up guide for examples of this.

Note

The examples below have been updated to use theReact.createRef() API introduced in React 16.3. If you are using an earlier release of React, we recommend usingcallback refs instead.

Creating Refs

Refs are created usingReact.createRef() and attached to React elements via theref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

classMyComponentextendsReact.Component{constructor(props){super(props);this.myRef= React.createRef();}render(){return<divref={this.myRef}/>;}}

Accessing Refs

When a ref is passed to an element inrender, a reference to the node becomes accessible at thecurrent attribute of the ref.

const node=this.myRef.current;

The value of the ref differs depending on the type of the node:

  • When theref attribute is used on an HTML element, theref created in the constructor withReact.createRef() receives the underlying DOM element as itscurrent property.
  • When theref attribute is used on a custom class component, theref object receives the mounted instance of the component as itscurrent.
  • You may not use theref attribute on function components because they don’t have instances.

The examples below demonstrate the differences.

Adding a Ref to a DOM Element

This code uses aref to store a reference to a DOM node:

classCustomTextInputextendsReact.Component{constructor(props){super(props);// create a ref to store the textInput DOM elementthis.textInput= React.createRef();this.focusTextInput=this.focusTextInput.bind(this);}focusTextInput(){// Explicitly focus the text input using the raw DOM API// Note: we're accessing "current" to get the DOM nodethis.textInput.current.focus();}render(){// tell React that we want to associate the <input> ref// with the `textInput` that we created in the constructorreturn(<div><inputtype="text"ref={this.textInput}/><inputtype="button"value="Focus the text input"onClick={this.focusTextInput}/></div>);}}

React will assign thecurrent property with the DOM element when the component mounts, and assign it back tonull when it unmounts.ref updates happen beforecomponentDidMount orcomponentDidUpdate lifecycle methods.

Adding a Ref to a Class Component

If we wanted to wrap theCustomTextInput above to simulate it being clicked immediately after mounting, we could use a ref to get access to the custom input and call itsfocusTextInput method manually:

classAutoFocusTextInputextendsReact.Component{constructor(props){super(props);this.textInput= React.createRef();}componentDidMount(){this.textInput.current.focusTextInput();}render(){return(<CustomTextInputref={this.textInput}/>);}}

Note that this only works ifCustomTextInput is declared as a class:

classCustomTextInputextendsReact.Component{// ...}

Refs and Function Components

By default,you may not use theref attribute on function components because they don’t have instances:

functionMyFunctionComponent(){return<input/>;}classParentextendsReact.Component{constructor(props){super(props);this.textInput= React.createRef();}render(){// This will *not* work!return(<MyFunctionComponentref={this.textInput}/>);}}

If you want to allow people to take aref to your function component, you can useforwardRef (possibly in conjunction withuseImperativeHandle), or you can convert the component to a class.

You can, however,use theref attribute inside a function component as long as you refer to a DOM element or a class component:

functionCustomTextInput(props){// textInput must be declared here so the ref can refer to itconst textInput=useRef(null);functionhandleClick(){    textInput.current.focus();}return(<div><inputtype="text"ref={textInput}/><inputtype="button"value="Focus the text input"onClick={handleClick}/></div>);}

Exposing DOM Refs to Parent Components

In rare cases, you might want to have access to a child’s DOM node from a parent component. This is generally not recommended because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.

While you couldadd a ref to the child 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 function components.

If you use React 16.3 or higher, we recommend to useref forwarding for these cases.Ref forwarding lets components opt into exposing any child component’s ref as their own. You can find a detailed example of how to expose a child’s DOM node to a parent componentin the ref forwarding documentation.

If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can usethis alternative approach and explicitly pass a ref as a differently named prop.

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 usefindDOMNode(), but it is discouraged and deprecated inStrictMode.

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 aref attribute created bycreateRef(), 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 theref callback to store a reference to a DOM node in an instance property.

classCustomTextInputextendsReact.Component{constructor(props){super(props);this.textInput=null;this.setTextInputRef=element=>{this.textInput= element;};this.focusTextInput=()=>{// Focus the text input using the raw DOM APIif(this.textInput)this.textInput.focus();};}componentDidMount(){// autofocus the input on mountthis.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(<div><inputtype="text"ref={this.setTextInputRef}/><inputtype="button"value="Focus the text input"onClick={this.focusTextInput}/></div>);}}

React will call theref callback with the DOM element when the component mounts, and call it withnull when it unmounts. Refs are guaranteed to be up-to-date beforecomponentDidMount orcomponentDidUpdate fires.

You can pass callback refs between components like you can with object refs that were created withReact.createRef().

functionCustomTextInput(props){return(<div><inputref={props.inputRef}/></div>);}classParentextendsReact.Component{render(){return(<CustomTextInputinputRef={el=>this.inputElement= el}/>);}}

In the example above,Parent passes its ref callback as aninputRef prop to theCustomTextInput, and theCustomTextInput passes the same function as a specialref attribute to the<input>. As a result,this.inputElement inParent will be set to the DOM node corresponding to the<input> element in theCustomTextInput.

Legacy API: String Refs

If you worked with React before, you might be familiar with an older API where theref attribute is a string, like"textInput", and the DOM node is accessed asthis.refs.textInput. We advise against it because string refs havesome issues, are considered legacy, andare likely to be removed in one of the future releases.

Note

If you’re currently usingthis.refs.textInput to access refs, we recommend using either thecallback pattern or thecreateRef API instead.

Caveats with callback refs

If theref callback is defined as an inline function, it will get called twice during updates, first withnull 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 theref callback as a bound method on the class, but note that it shouldn’t matter in most cases.

Is this page useful?Edit this page

[8]ページ先頭

©2009-2025 Movatter.jp