create a ref in React code example
Example 1: 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 2: cre&atRefs react js
const node = this.myRef.current;
Example 3: use ref in component reactjs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
Example 4: use ref in component reactjs
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
this.textInput.current.focus(); }
render() {
return (
<div>
<input
type="text"
ref={this.textInput} /> <input
type="button"
value="Donner le focus au champ texte"
onClick={this.focusTextInput}
/>
</div>
);
}
}