how to use refs in functional component code example
Example 1: react.createref()
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.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 node
this.textInput.current.focus(); }
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} /> <input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
Example 2: when to use react ref
WHEN TO USE REACT'S REF ATTRIBUTE?
But it is not always a good idea to use the ref attribute. The general rule of thumb is to avoid it. The official React documentation mentions three occasions where you can use it because you have no other choice.
Managing focus, text selection, or media playback.
Integrating with third-party DOM libraries.
Triggering imperative animations.
Example 3: cre&atRefs react js
const node = this.myRef.current;
Example 4: createref in functional component
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
</div>
);
}
Example 5: use ref in component reactjs
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => { this.textInput = element; };
this.focusTextInput = () => { // Donne le focus au champ texte en utilisant l’API DOM native. if (this.textInput) this.textInput.focus(); }; }
componentDidMount() {
// Focus automatique sur le champ au montage
this.focusTextInput(); }
render() {
// Utilise la fonction de rappel `ref` pour stocker une référence à l’élément
// DOM du champ texte dans une propriété d’instance (ex. this.textInput)
return (
<div>
<input
type="text"
ref={this.setTextInputRef} />
<input
type="button"
value="Donner le focus au champ texte"
onClick={this.focusTextInput} />
</div>
);
}
}
Example 6: use ref in component reactjs
class CustomTextInput extends React.Component { // ...
}