Author avatar

Gaurav Singhal

Creating <select> Elements in React

Gaurav Singhal

  • Jun 15, 2020
  • 6 Min read
  • 110 Views
  • Jun 15, 2020
  • 6 Min read
  • 110 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React supports all types of DOM HTML elements, which can be used to implement forms or other functionalities with various components such as text inputs, file uploads, selects, radio buttons, and checkboxes.

In web app development, you may need to create elements dynamically based on certain conditions. In this guide, you'll learn how to create a dynamic select element and render the dynamic options of the select element.

Create a Dynamic Select Element

A select element is a common element that allows a user to select a specific element from a list of available options. A select element can be created two different ways: using the static element into the DOM or adding it dynamically into the DOM.

Below are some examples that require the Axios package, which helps you grasp the process of creating dynamic select elements. Axios is an HttpClient that helps to make HTTP requests such as GET, POST, PUT, and DELETE.

Install Axios with this code:

1
npm install axios
powershell

Now that you have installed the package, create a dummy example to demonstrate the dynamic select element. Refer to the component App.js and implement the AXIOS GET API call as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { Component } from "react";
import { render } from "react-dom";
import DynamicSelect from "./DynamicSelect";
import axios from "axios";

class App extends Component {
  constructor() {
    super();
    this.state = {
    };
  }

  componentDidMount() {
    var self = this;
    axios
      .get("https://reqres.in/api/users?page=1", {
        mode: "no-cors"
      })
      .then(function(response) {
        self.setState({ users: response.data.data });
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  render() {
    const { users } = this.state;
    return (
      <div>
        <DynamicSelect users={users} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
jsx

In the above example, the Axios API call implements into the life-cycle hook componentDidMount().

So once the response is successful, the details get added into the state variable users, as shown below.

1
2
3
.then(function(response) {
    self.setState({ users: response.data.data });
})
jsx

After getting the values from the state, the next step is to send the data to the child component, as shown below.

1
2
3
4
5
6
7
8
render() {
    const { users } = this.state;
    return (
      <div>
        <DynamicSelect users={users} />
      </div>
    );
}
jsx

Now, define the component DynamicSelect.jsx, which is used in the above code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { Component } from "react";

class DynamicSelect extends Component {
  constructor() {
    super();
    this.onChangeUser = this.onChangeUser.bind(this);
  }

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

  render() {
    const { users } = this.props;
    
    return (
      <div>
        This is dynamic select element demo
        <div>
          <span>Select user</span> :
          {users && users.length > 0 && (
            <div>
              /* Adding dynamic select element */
              <select onChange={this.onChangeUser}>
                {users.map((user, index) => {
                  return <option>{user.email}</option>;
                })}
              </select>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default DynamicSelect;
jsx

Let’s now look at each functionality implemented into the above component.

Inside the render() function, you will observe that there is one condition that identifies sufficient values coming from the props users.

1
{users && users.length > 0 && () }
jsx

So once there are sufficient records found from the props users, then the dynamic <select> element is created; otherwise, it is not created.

And once the user changes the selected value, it reflects the event and can be used as shown below.

1
2
3
onChangeUser(event) {
    console.log(event.target.value);
}
jsx

This way, you can create the dynamic <select> element based on the condition or your custom business logic and render the same into the DOM.

An Alternate Way to Render Dynamic options

In the above example, to map the users, I have used the map() function, which is coming from the parent component called App.

You could also implement the function that returns the dynamic <options>, and the options could be added inside the <select> element.

1
2
3
4
5
6
7
8
9
10
11
12
13
render() {
    return (
      <div>
        This is dynamic select element demo
        <div>
          <span>Select user</span> :{" "}
          <select onChange={this.onChangeUser}>
            {this.renderOptions()}
          </select>
        </div>
      </div>
    );
}
jsx

Inside the <select> element, you will find there is one function that has been called this.renderOptions(), which is supposed to return the dynamic <options>, which can be implemented as follows.

1
2
3
4
5
6
7
8
9
10
renderOptions() {
    const { users } = this.props;
    return (
      users &&
      users.length > 0 &&
      users.map((user, index) => {
        return <option>{user.email}</option>;
      })
    );
}
jsx

From the function renderOptions(), the dynamic list of users can be returned, and it could be consumed inside the <select> element.

This is an implementation used to normalize the code and helps to structure the component straightforwardly.

Conclusion

A React app may contain dynamic form fields, including a <select> element, which includes multiple options to choose from.

In this guide, you have learned the standard mechanism for adding a dynamic <select> and <options> elements based on the condition. I hope it helps you implement dynamic form controls into your React app.

0