Refs and function component in react
By default, you may not use the ref attribute on function components because they don’t have instances. If you want to allow people to take a ref to your function component, you can use forwardRef (possibly in conjunction with useImperativeHandle), or you can convert the component to a class.
Ref not working in react function component
 1 function MyFunctionComponent() {
 2   return <input />;
 3 }
 4 
 5 class Parent extends React.Component {
 6   constructor(props) {
 7     super(props);
 8     this.textInput = React.createRef();
 9   }
 10   render() {
 11     // This will *not* work!
 12     return (
 13       <MyFunctionComponent ref={this.textInput} />
 14     );
 15   }
 16 }
however, if you want to use the ref attribute inside a function component you can refer to a DOM element or a class component:
Function component with Ref
 1 function CustomTextInput(props) {
 2   // textInput must be declared here so the ref can refer to it
 3   const textInput = useRef(null);
 4   
 5   function handleClick() {
 6     textInput.current.focus();
 7   }
 8 
 9   return (
 10     <div>
 11       <input
 12         type="text"
 13         ref={textInput} />
 14       <input
 15         type="button"
 16         value="Focus the text input"
 17         onClick={handleClick}
 18       />
 19     </div>
 20   );
 21 }

Callback Refs in react component

React also supports another way to set refs called “callback refs”, which gives more fine-grain control over when refs are set and unset.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us