What is a React Ref?

A reference to value, function, DOM or React Element

About

A ref is a state object that holds a value in its current property for the entire lifetime of the component.

  • It's used to hold information that isn’t used for rendering.
  • Unlike with state, updating a ref does not re-render your component.
  • It's the equivalent of a field in class component for functional components.

Example of values

  • A timeout ID
  • A HTML DOM node element. React will put a ref property in every element that holds the HTML DOM node element.

Example with Reference on a Dom element

An class component example that will show you how to read the value of an input element.

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.input = React.createRef();
    console.log("At its creation, the ref.current value is "+this.input.current);
  }

  handleClick(event) {
    console.log('The ref gives access to the HTML element via current: ' + this.input.current.__proto__.toString());
    console.log('where you have access to all HTML attribute such as the value');
    console.log('Example: the value submitted was: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <div>
        <label>
          Name:
          <input type="text" ref={this.input} defaultValue="ChangeMe" />
        </label>
        <button onClick={this.handleClick}>Read the value</button>
      </div>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<div id="root"></div>

Note that in React, you define the default value with the attribute defaultValue and not value.

Usage

Setting a global runtime value

Referencing a value that will persist and stay the same on the next renders (React component or React HTML element) to be able to manipulate them.

Avoiding new initialization

Avoiding new initialization of value or function. React performs the initialization of the ref value once and ignores it on the next renders.

Manipulating the DOM

A Parent component can set a reference on one more child React elements.

Note that once a component unmounts, React:

  • set ref.current to null if ref is a value
  • or call the ref function with null if ref is a callback function.

Due to the DOM manipulation, you can:

  • track mount and unmount of component
  • Manage focus, text selection, or media playback.
  • Trigger imperative animations.
  • Integrating with non-React systems such as third-party DOM libraries or the built-in browser APIs.

Example: In this example:

  • we set a ref to an input html react element
  • we change its value via the DOM element that is accessible through the Ref
const Input = function() {

  const input = React.useRef();

  React.useEffect(function(){
    console.log('The DOM element is a '+ input.current.__proto__.toString());
    const newValue = "Use Effect Value";
    console.log('We can change its value to ('+newValue+') via the DOM element');
    input.current.value = newValue;
  },[input])

  return (
      <input type="text" ref={input} value="first Render value"/>
  );
    
}

Management

Creation

Refs are created using:

  • React.createRef() (since 16.3)
  • or the hook for function component

Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

Refs are attached to React elements via the ref attribute.

Something like that:

const ref = React.createRef();
return ( 
   <input type="text" ref={ref} defaultValue="ChangeMe" />
)

Hook

React has a Hook to create Ref. See useRef





Discover More
Card Puncher Data Processing
D3 - React

D3 in react By using the ref attribute
Examples of React Input Element with Class component

This page keeps the example with class component for a input The react forms components input accept a value attribute that is used to implement a controlled component. A React form: written as...
React - Children Element

When you create an element, you pass one or more children elements that will build the React DOM tree. componentyou create a component Related: See also The below example codes are created with JSX....
React - Composite Component (Layout) / Container Component

React Layout / Composition - There is three methods to create a composite component from html component / or composite (decorator) Props: via props but alsoRefs (They provide a way...
React - Forwarding Ref

The forwardRef function wraps a element to add to the props a ref that is generated by React. This ref is called a forwarding ref because you pass it along to use it in one of its child components in...
React - Input Element

This page is the handling of input element in React. These examples are made with a function components. If you still want to see the same example with class component, they are here: The react...
React - State

This page is UI State in React. The Local state to a component in react is known as: state. A change of state triggers a render ref. A change of ref value does not triggers a render The global...
React - Uncontrolled Component (DOM State)

An uncontrolled component is a component such as form where the state is handled by the DOM itself (not react) controlled component if: you need to write an very difficult event handler (for every...
What are React HTML elements? (Built-In)

In React, HTML elements are: built-in React elements that wraps a HTML element the leaf of the React DOM tree In Jsx A css class that we will apply to our HTML element The component with...



Share this page:
Follow us:
Task Runner