Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Set Focus on a React-Bootstrap Input Field Using refs.x.getDOMNode.focus

Jul 8, 2020 • 5 Minute Read

Introduction

React Bootstrap is a popular library for integrating React-ready Bootstrap user interface components. Forms are a standard part of any application, and various form controls such as text inputs, dropdowns, file uploads, radio buttons, and checkboxes are required to behave dynamically. But sometimes users submit forms with errors, such as missing required information or an invalid value. Setting focus on an input control highlights a specific input box that has an error.

In this guide, you will learn how to set focus on a React Bootstrap input control using the ref and getDOMNode() functions.

Set Focus Using refs.x.getDOMNode.focus

The React Bootstrap input control can be created inside the <Form> control, which is a part of the React Bootstrap library.

The next step is to import the required form controls from react-bootstrap, and from react-dom as given below.

      import ReactDOM from 'react-dom';
import { Form, Button } from "react-bootstrap";
    

Now, set up the form with the input control and a button.

      render() {
    return (
      <div>
        <span>Simple bootstrap input focus</span>
        <div>
          <Form>
            <Form.Group controlId="myFormGroup">
              <Form.Label>Email id :</Form.Label>
              <Form.Control
                type="email"
                placeholder="Enter your email"
              />
            </Form.Group>
            <Button
              variant="primary"
              type="button"
            >
              FOCUS
            </Button>
          </Form>
        </div>
      </div>
    );
}
    

This is a basic form without a ref or button click event. The next move is to update the form control by adding the ref as shown below.

      <Form.Group controlId="formBasicEmail">
    <Form.Label>Email address</Form.Label>
    <Form.Control
        ref={c => (this.myInputRef = c)}
        type="email"
        placeholder="Enter email"
    />
</Form.Group>
    

There is one added property called ref with the form control used to get the reference of the input control.

After adding ref, the next thing is to add the button click event as shown below.

      <Button
    variant="primary"
    onClick={this.setInputFocus}
    type="button"
    >
    FOCUS
</Button>
    

The button click event is one of the most important parts of this demo because once the user clicks on the button, the input control is focused.

      setInputFocus() {
    ReactDOM.findDOMNode(this.myInputRef).focus();
}
    

Here are a few important you need to understand.

ReactDOM: The ReactDOM is a collection of methods used to modify the behavior of the various DOM elements into the components.

findDOMNode: The findDOMNode helps to get access to the specific DOM node from the DOM tree, and it can also be used to access the values coming from that DOM node.

focus(): The focus method is mostly used along with the text element. It allows you to highlight the underlying HTML element.

Below is the complete code to focus on an input element.

      import React, { Component } from "react";
import ReactDOM from 'react-dom';
import { Form, Button } from "react-bootstrap";

class BootstrapInput extends Component {
  constructor() {
    super();
    this.setInputFocus = this.setInputFocus.bind(this);
  }

  setInputFocus() {
    ReactDOM.findDOMNode(this.myInputRef).focus();
  }

  render() {
    return (
      <div>
        <span>Simple bootstrap input focus</span>
        <hr />
        <div>
          <Form>
            <Form.Group controlId="formBasicEmail">
              <Form.Label>Email address</Form.Label>
              <Form.Control
                ref={c => (this.myInputRef = c)}
                type="email"
                placeholder="Enter email"
              />
            </Form.Group>
            <Button
              variant="primary"
              onClick={this.setInputFocus}
              type="button"
            >
              FOCUS
            </Button>
          </Form>
        </div>
      </div>
    );
  }
}

export default BootstrapInput;
    

Focus Input Without Using findDOMNode

You have learned how to focus on a React Bootstrap input element using findDOMNode, but alternatively, it can also be achieved by just using the ref.

There is one simple change while accessing the DOM element as shown below.

      setInputFocus() {
    this.myInputRef.focus();
}
    

The focus() method directly uses ref and the input element can be focused.

Note: findDOMNode() is deprecated in strict mode, and from now on only ref is sufficient to access the DOM nodes directly.

Conclusion

React supports DOM manipulation methods and property by using the package react-dom, which allows us to access and manipulate the DOM element's behavior.

In this guide, you have seen two different approaches to focus the input element: one using findDOMNode() along with focus(), and one using just the element ref. I hope this guide helps you access the DOM elements.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author