You have probably used the useRef hook to access DOM nodes.
If you search for articles on ref, this is the most common example you’d find
import React, { Component, createRef } from "react"; class CustomTextInput extends Component {
textInput = createRef();
focusTextInput = () => this.textInput.current.focus();
render() {
return (
<>
<input type="text" ref={this.textInput} /><button onClick={this.focusTextInput}>Focus the text input</button> </>
);
}
}
The above example shows how you’ll use refs if you have a class component.
If you are using functional components, this is the approach you’ll take to achieve the same thing,
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
#javascript #react-native #react