Understanding refs and how to use them
In the usual workflow, React components communicate with their children by passing props
. However, there are a few cases where it's needed to access the instance of a child to communicate or modify its behavior. React uses refs
to allow us to access the instance of a child.
It's important to understand that React components' instances give you access to their instance methods and properties. However, an instance of a React element is an instance of an HTML DOM element. Refs are accessed by giving a ref
attribute to the React component or React element. It expects the value to be a callback function that will be invoked once the instance is created, providing a reference to the instance in the first argument passed to the callback function.
React provides a helper function named createRef
to define function callbacks for setting refs correctly. Take, for example, the following code, which obtains a reference of a React component and a React element:
class...