I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand
Refs are a way to set a variable at a DOM element or a class component instance.
There are two types of refs: callback refs, and object refs.
Object refs are created using useRef()
or React.createRef()
.
To use them (an example with a function component referencing a DOM element):
Declare a "container" variable (which you will point at a DOM element in the next step) and set it equal to useRef()
. This is your "ref object."
Add a ref
attribute to your DOM element. Set it equal to your ref
object.
Now this ref
object represents the DOM element you pointed it at, and can be used to access its methods and properties.
function InputField() {
const refForInput = useRef(); // 1. initializing `refForInput` as a reference object.
return (
//2. passing it to the input element as its ref
// 3. now, calling `refForInput` will refer to the DOM element, and you can access its `focus()` method.
)
}
The process is similar if using class components; see the React docs for details.
Callback refs function similarly, but allow more fine-grained control.
To create a callback ref, you similarly add a ref
attribute to your DOM element, but instead of passing in a ref
object, you pass in a callback. This callback receives the element itself as the argument for the callback; you can then set it equal to an existing value (this.something
in a class; an already-declared variable in a function component.)
Here's an annotated vversion of the example from Avid Programmer's excellent example; see his answer for an example with classes.
function CustomForm({handleSubmit}) {
let inputElement;
return (
)
}
Note that the callback will be called with null
when the component unmounts.
They shouldn't be used often; they're meant as escape hatches. They allow you to access API methods (focus()
is a common example) available on the actual html elements that may not be available on the React component. If this seems confusing, remember that a React button component, for example, is not the same as an html button component. You can call focus()
on an html button element, but not on a React button element.