MENU
Child Access
Refs allow access to the methods and fields of:
HTML DOM nodes or
child React elements
in the render() method.
Below, the text field is automatically focused after the document has been loaded.
RESETRUNFULL
RESETRUNFULL
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInputRef = React.createRef();
}
focusTextInput() { // (1) accessing method of DOM node
this.textInputRef.current.focus();
}
render() {
return (<input type="text" ref={this.textInputRef} />);
}}class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() { // (2) accessing method of child React component
this.textInput.current.focusTextInput();
}
render() {
return (<CustomTextInput ref={this.textInput} />);
}}ReactDOM.render(<AutoFocusTextInput />, document.querySelector('div'));