1WHEN TO USE REACT'S REF ATTRIBUTE?
2But 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.
3
4Managing focus, text selection, or media playback.
5Integrating with third-party DOM libraries.
6Triggering imperative animations.
1class MyComponent extends React.Component {
2 constructor(props) {
3 super(props);
4 this.myRef = React.createRef(); }
5 render() {
6 return <div ref={this.myRef} />; }
7}
1function CustomTextInput(props) {
2 // textInput doit être déclaré ici pour que la ref puisse s’y référer const textInput = useRef(null);
3 function handleClick() {
4 textInput.current.focus(); }
5
6 return (
7 <div>
8 <input
9 type="text"
10 ref={textInput} /> <input
11 type="button"
12 value="Donner le focus au champ texte"
13 onClick={handleClick}
14 />
15 </div>
16 );
17}