Using ref Attribute

    To make a reference, place the ref attribute with a function value on any React element or component. Then, inside of the function, the first parameter within the scope of the function will be a reference to the element or component the ref is on.

    A common use for ref‘s are to store a reference on the component instance. In the code below I use the ref callback function on the text <input> to store a reference on the component instance so other instance methods have access to the reference via this (i.e., this.textInput.focus()).

    • You might see a ref attribute with a string instead of a function; this is called a string and will likely be deprecated in the future. Function refs are preferred.
    • References to a component instance allow one to call custom methods on the component if any are exposed when defining it.
    • React makes two suggestions when using refs: “Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive props and state. They should, however, not be your go-to abstraction for flowing data through your application. By default, use the Reactive data flow and save refs for use cases that are inherently non-reactive.” and “If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use refs to “make things happen” – instead, the data flow will usually accomplish your goal.”