React - Ref

About

A ref is a reference to:

Parent components can get the element by reference and manipulate them

Usage

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Example

Dom element

input example with a Uncontrolled Component

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

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

  handleSubmit(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 name submitted was: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} defaultValue="ChangeMe" />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

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

Management

Creation

Refs are created using React.createRef() (since 16.3)

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

Attach

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. See useRef

Documentation / Reference


Powered by ComboStrap