ReactJS Refs Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- React Refs

In ReactJS, refs are used as reference to an element for you. Basically, it is advisable to avoid using the refs in most cases. However, it is useful when you want to access the DOM nodes or elements created in the render() method.
Note: In this lesson, I will create Refs by the style of ReactJS, version 16.3, because it is easier for use.
Use the React.createRef() method to create Refs, and then attach them to the elements (created in render() ) through the ref property.

class MyComponent extends React.Component {
  constructor(props) {

    this.myRef = React.createRef();

  render() {
    return <div ref={this.myRef} />;

When a Ref is attached to an element create in the render() method, you may refer to the Node object of this element through the current property of the Ref.

const node = this.myRef.current;

class SearchBox extends React.Component {
  constructor(props) {
    this.state = {
      searchText: "reactjs"
    this.searchFieldRef = React.createRef();

  clearAndFocus() {
    this.setState({ searchText: "" });
    // Focus to Input Field.
    this.searchFieldRef.current.style.background = "#e8f8f5";

  changeSearchText(event) {
    var v = event.target.value;
    this.setState((prevState, props) => {
      return {
        searchText: v

  render() {
    return (
      <div className="search-box">
          onChange={event => this.changeSearchText(event)}
        <button onClick={() => this.clearAndFocus()}>Clear And Focus</button>
        <a href="">Reset</a>

// Render
ReactDOM.render(<SearchBox />, document.getElementById("searchbox1"));

<!DOCTYPE html>
<html lang="en">
      <meta charset="UTF-8">
      <title>ReactJS Refs</title>
      <script src="https://unpkg.com/react@16.4.2/umd/react.production.min.js"></script>
      <script src="https://unpkg.com/react-dom@16.4.2/umd/react-dom.production.min.js"></script>
      <script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
         .search-box  {
         border:1px solid #cbbfab;
         padding: 5px;
         margin: 5px;
      <h3>React Refs:</h3>
      <div id="searchbox1"></div> 
      <script src="refs-example.jsx" type="text/babel"></script>

2- Callback Refs (TODO)

View more Tutorials: