How to Retrieve the Selected Value from a Select Field in ReactJS and NextJS
Welcome back to the Devmaesters website! In this article, I'll show you how to retrieve the value of a select/dropdown field the moment a user selects an option in React/Next.js.
To begin with lets create a simple react component as shown below
import React from 'react'
function SelectField() {
return (
<select >
<option>Mainnet</option>
<option>Testnet</option>
<option>Devnet</option>
</select>
)
}
export default SelectField;
This is a simple select field in jsx that contains 3 options (mainnet, testnet and devnet). The goal is to get the selected value the moment the user toggles from one value to another.
Next thing you need to do is to add an onChange attribute and create a javascript function to handle the change as shown below
import React from 'react'
function SelectField() {
const handleChange = (e) => {
console.log("Value", e)
}
return (
<select onChange={(e) => handleChange(e.target.value)}>
<option>Mainnet</option>
<option>Testnet</option>
<option>Devnet</option>
</select>
)
}
export default SelectField;
The e.target.value returns the currently selected option and is passed to the handlechange function through the function parameters which is then consoled out.
Conclusion
This has been a short article on how to get the value of a select field when a user selects an option in react/next js. If you run into any issues using the method above hen feel free to leave a comment down below and i will help you to resolve it. As alaways thanks for reading.