• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

153
Vistas
React get value from select dropdown populated from API

I have a select component:

<Select}>
    {data &&
        data.map((survey) => (
            <Option key={survey.id} value={survey.id}>
                {survey.name}
            </Option>
        ))
     }
</Select>

The data array is coming from an API fetch using axios, which is then saved in the state data:

const [data, setData] = useState([]);

How do I grab the selected value and display it?

I tried adding an onChange handler to the component and save the e.target.value in a separate piece of state:

onChange={e => setInput(e?.target?.value)}

However, I'm getting an error that value is undefined. I suspect it's because the data hasn't loaded yet.

How do you get the selected value from the options when the options are coming from an API? (i.e., dynamic dropdown)

about 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Try like this :

  const [data, setData] = useState([]);
  const handleChange = (e) => {
    console.log(e.target.value);
    setData(e.target.value);
  };

   <select onChange={handleChange}>
      {dataArr &&
        dataArr.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>

Example : Example

about 3 years ago · Juan Pablo Isaza Denunciar

0

You need to define a new state and set it in onChange handler to show the selected data at somewhere else.

Define it as:

const [selectedValue,setSelectedValue] = useState()

Then, set it:

const handleChange = (e) => { 
    setSelectedValue(e.target.value)
}

it is now available to use anywhere in this component.

Here is an example:

import React, { useState, useEffect } from 'react';

export default function App() {
  const [data, setData] = useState([]);
  const [selectedValue,setSelectedValue] = useState()

// this useEffect is just a simulator for api response, you do not need this useEffect, 
// instead just call your api and set the data with your awaited response
  useEffect(()=>{ 
    setTimeout(()=> {
      setData([ 
        { name: 'first Option', id: 'ID of first option'},
        { name: 'Second Option', id: 'ID of second option' }
      ])
    },[2000])
  },[])

  const handleChange = (e) => { 
    console.log(e.target.value); // maybe print the value to check
    setSelectedValue(e.target.value)
  }
  
  return (<div>
    <select onChange={handleChange}>
      {data &&
        data.map((survey) => (
          <option key={survey.id} value={survey.id}>
            {survey.name}
          </option>
        ))}
    </select>
    {selectedValue ? <div>Selected value:  {selectedValue} </div> : ''}
  </div>
  );
}
about 3 years ago · Juan Pablo Isaza Denunciar

0

Can you confirm that the value attribute on the option tag is properly set and it has the value you want it to have.

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda