How to get a select element's value in React-Bootstrap
React-Bootstrap, a complete reimplementation of the popular CSS framework Bootstrap in React, offers a set of ready-to-use
Example
The React application consists of a select component with different options. When we select an option from the drop-down menu, its value is displayed below it. The UI of the application is as follows.
Implementation
To create this basic UI, go to the App.js file and replace the app function with the following:
{/*importing required libraries*/}import React, { useState } from 'react';import { Form } from 'react-bootstrap';import './App.css';function App() {{/*using the useState hook update the values*/}const [selectedValue, setSelectedValue] = useState('');{/*taking the value of select element and updating it through the function*/}const handleSelectChange = (event) => {setSelectedValue(event.target.value);};return (//code for application UI<div className="App"><h1>React Bootstrap Select Example</h1>{/*an input that has multple options*/}<Form><Form.Group controlId="exampleForm.ControlSelect1"><Form.Label>Select an option</Form.Label>{/*Implementing the method to update the value once changed*/}<Form.Control as="select" value={selectedValue} onChange={handleSelectChange}><option value="option1">Option 1</option><option value="option2">Option 2</option><option value="option3">Option 3</option></Form.Control>{/*Outputing the changed value*/}</Form.Group><p>Selected Value: {selectedValue}</p></Form></div>);}export default App;
Explanation
Line 1–6: We first import the
useStatehook from thereactlibrary. Then, we import theFormcomponent fromreact-bootstrap. We also importApp.cssfor styling of the application.Line 8–13: Using the
useStatehook, we declareselectedValueandsetselectedValue. Through thesetselectedValuemethod, we get the latest value of the component and then updateselectedValuethrough thehandleSelectChangemethod.Line 15–22: We create a basic Form application using the
Formcomponent ofreact-bootstraplibrary.Line 24–37: We assign the value of the select component to the
selectedValuestate variable defined on line 8. We also sethandleSelectChangeas theonChangemethod to update the state variable whenever the value of the select component changes and display it in the web application.
Code
Click on the “Run” button below to start the React application. Then, click the link below the “Run” button to view and interact with the application.