Creating <select> Elements in React
Jun 15, 2020 • 6 Minute Read
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:
npm install axios
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.
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"));
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.
.then(function(response) {
self.setState({ users: response.data.data });
})
After getting the values from the state, the next step is to send the data to the child component, as shown below.
render() {
const { users } = this.state;
return (
<div>
<DynamicSelect users={users} />
</div>
);
}
Now, define the component DynamicSelect.jsx, which is used in the above code.
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;
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.
{users && users.length > 0 && () }
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.
onChangeUser(event) {
console.log(event.target.value);
}
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.
render() {
return (
<div>
This is dynamic select element demo
<div>
<span>Select user</span> :{" "}
<select onChange={this.onChangeUser}>
{this.renderOptions()}
</select>
</div>
</div>
);
}
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.
renderOptions() {
const { users } = this.props;
return (
users &&
users.length > 0 &&
users.map((user, index) => {
return <option>{user.email}</option>;
})
);
}
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.