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.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.