Get the value of <select> dropdown in ReactJs

Viewed 40

I am pretty new to web development, I want to be able to retrieve the value in the select that is selected in the below code, but I am unable to.

I want to get it in a variable in order to send it using api. I am able to open the dropdown meni and able to

import {useHistory} from 'react-router-dom'
import { useForm, FormActions } from '../../context/FormContext'
import { Theme } from '../../components/Theme/intex'
import { ChangeEvent, useEffect } from 'react'


export const FormStep1 = () => {


    const history = useHistory()
    const { state, dispatch} = useForm()

    const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
        dispatch({
            type: FormActions.setName,
            payload: e.target.value
        })
    }

    const handleNextStep = () =>{
        if(state.name !== '') {
            history.push('/step2')
        } else{
            alert('Please enter your details')
        }
        state.team = 'test'

    }

    useEffect(()=>{
        dispatch({
            type: FormActions.setCurrentStep,
            payload: 1
        })

    },[])

    
    return(
        <Theme>
            <C.Container>
                <p className='Step'>Step 1/3</p>
                <h2>Team Name</h2>
                <p>Select Existing Team or Create a New Team</p>

                <label> Select your team_usecase </label>
                <select name="pets" id="pet-select">
                    <option value=""> Select your team </option>
                    <option value="dog">dog</option>
                    <option value="cat">cat</option>
                    <option value="hamster">hamster</option>
                    <option value="parrot">parrot</option>
                    <option value="spider">spider</option>
                    <option value="goldfish">Goldfish</option>
                </select>
    )
}```


I was able to find a few solutions but I couldn't get them to work, so any help would be appreciated.
1 Answers

You can achieve this by putting onChange handler on select like this:

return(
        <Theme>
            <C.Container>
                <p className='Step'>Step 1/3</p>
                <h2>Team Name</h2>
                <p>Select Existing Team or Create a New Team</p>

                <label> Select your team_usecase </label>
                <select name="pets" id="pet-select" onChange=(e => handleNameChange(e))>
                    <option value=""> Select your team </option>
                    <option value="dog">dog</option>
                    <option value="cat">cat</option>
                    <option value="hamster">hamster</option>
                    <option value="parrot">parrot</option>
                    <option value="spider">spider</option>
                    <option value="goldfish">Goldfish</option>
                </select>
            </C.Container>
        </Theme>
)
Related