Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
refs

What are React refs?

Educative Answers Team

React refs are used to access the DOM or React elements that were created in the render method. According to the official documentation​, refs should be used to:

  1. Manage focus, media playback, or text selection.
  2. Integrate with third-party DOM libraries.
  3. Trigger animations.

Three ways used to create refs in React are:

  • string refs (this method is deprecated)
  • callback refs
  • createRef() refs (this is a recent addition)

Code

In the examples below, a ref is used to access the user input and set the background color to a specified color.

1. Using callbacks

The following code snippet demonstrates how a ref can be created using a callback:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

2. Using createRef()

Starting from version 16.3, React included a new createRef() method that can be used for creating refs. The following code snippet demonstrates how a ref can be created using the createRef() method:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

RELATED TAGS

react
refs
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring