Sometimes, we want to attach to a stateless component’s ref in React.
In this article, we’ll look at how to attach to a stateless component’s ref in React.
How to attach to a stateless component’s ref in React?
To attach to a stateless component’s ref in React, we can use the useRef
hook.
For instance, we write
const CustomTextInput = (props) => {
const textInput = useRef();
const handleClick = () => {
textInput.current.focus();
};
return (
<div>
<input type="text" ref={textInput} />
<input type="button" value="Focus the text input" onClick={handleClick} />
</div>
);
};
to create the textInput
ref with the useRef
hook,
Then we assign the set the ref
prop’s value to textInput
.
And then we can access the input element from textInput.current
as we have in handleClick
.
Conclusion
To attach to a stateless component’s ref in React, we can use the useRef
hook.