Skip to content

Contact sales

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

How to Get a Select Element's Value in React Bootstrap

Jun 3, 2020 • 6 Minute Read

Introduction

React uses one-way data binding, which means it can traverse data from components to view or from view to components. Two-way data binding is also possible by using the events attached to the elements.

In this guide, you'll learn how to use simple React Bootstrap select elements. You will also learn how to get the selected value from the select element using ref and form elements. HTML doesn't allow changing components directly, but it's possible using the event handler. One-way data binding sends the value, and then HTML can be rendered inside the DOM.

Using the Select Element

The select element is typically used to ask for multiple options and let the user select any of the options from the list using the click event.

Below is a simple implementation of the select element.

      import React, { Component } from "react";
import { Form } from "react-bootstrap";

class SimpleSelect extends Component {
  onChangeColor() {
    console.log(event.target.value);
  }

  render() {
    return (
      <div>
        Simple select element of react-bootstrap
        <hr />
        Select any color :
        <Form.Control
          as="select"
          custom
          onChange={this.onChangeColor.bind(this)}
        >
          <option value="red">Red</option>
          <option value="blue">Blue</option>
          <option value="green">Green</option>
          <option value="black">Black</option>
          <option value="orange">Orange</option>
        </Form.Control>
      </div>
    );
  }
}

export default SimpleSelect;
    

In the above example, the form controls are created using the <Form.Control> tag as a type of select, as shown below.

      <Form.Control
    as="select"
    custom
    onChange={this.onChangeColor.bind(this)}
>
    

Along with the select element, there is an added property attached called onChange, which is used to get the updated value of the select element.

So, it is possible to get access to the updated value once its value changes, as shown below.

      onChangeColor() {
    console.log(event.target.value);
}
    

Using event.target.value, you can further process the value for different purposes, such as submitting the value to the database.

Get Select Element Value Using Ref

We have seen in the above example that the select element’s value is updated based on the onChange event, and now we will get the updated value using ref as well.

To get the reference of the element, we use ref, and its value can be accessed throughout the existing components.

The first step is to create ref in the React component.

      constructor() {
    super();
    this.myRef = React.createRef();
}
    

Now, the next step is to implement the react-bootstrap select element with the added ref property.

      render() {
    return (
      <div>
        Simple select element of react-bootstrap
        <hr />
        Select any color :
        <Form.Control
          as="select"
          custom
          ref={this.myRef}
        >
          <option value="red">Red</option>
          <option value="blue">Blue</option>
          <option value="green">Green</option>
          <option value="black">Black</option>
          <option value="orange">Orange</option>
        </Form.Control>
        <button onClick={this.onButtonClick}>Get color</button>
      </div>
    );
}
    

There is the added property ref along with the select element followed by the name of reference you created before.

But the important part is to access the selected option from the select element.

      onButtonClick() {
    console.log(this.myRef.current.value);
}
    

The statement extracts the current referenced element from the DOM, and further, it fetches the value based on the user interaction.

This is one of the less commonly used approaches because you have to give the reference to each of the elements from which you want to get the values.

Get Select Element Value using Form Controls

You've now used a simple select element to get the selected value using ref. Often, however, the select element will be part of the form element.

In that case, the select element’s value can also be fetched using the form element, by using the event handler attached to the select element.

      render() {
    return (
      <div>
        Simple select element of react-bootstrap
        <hr />
        <Form onSubmit={this.onFormSubmit.bind(this)} role="form">
          <Form.Group controlId="exampleForm.SelectCustom">
            <Form.Label>Select Color : </Form.Label>
            <Form.Control as="select" custom onChange={this.onChangeColor.bind(this)}>
              <option value="red">Red</option>
              <option value="blue">Blue</option>
              <option value="green">Green</option>
              <option value="black">Black</option>
              <option value="orange">Orange</option>
            </Form.Control>
          </Form.Group>
          <Button type="submit">Submit form</Button>
        </Form>
      </div>
    );
}
    

Now there are two different events implemented in the form, this.onSubmitForm(), that can be used to submit the form once a user clicks on the submit button.

      onFormSubmit(event) {
    event.preventDefault();
    console.log("Color value is :", this.state.color);
}
    

Another event, this.onChangeColor(), can be used to listen for the change event of the select element, as shown below.

      onChangeColor() {
    this.setState({ color: event.target.value })
}
    

Once the user changes the select element value, it is updated to the component state, and the same state value this.state.color value sends the data to the database for processing.

This approach is widespread because each form element maintains its state, and once the form is submitted, the updated value can be fetched from the state.

Conclusion

The select element is a common part of most forms out there to get selected values from the user. In this guide, you have learned how to get the value of the selected item from the select element using ref and the form element. I hope it will help as you play around with the select element.

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