Reputation: 327
I am new to react and I am trying to set a state from a selection in a dropdown box, but my state remains undefined.
This is the array of objects that I am using for the dropdown (categorias.js):
export const categorias_array = [
{
key: 1,
text: "Primera",
value: "1"
},
{
key: 3,
text: "Tercera",
value: "3"
},
{
key: 4,
text: "Cuarta",
value: "4"
},
{
key: 5,
text: "Quinta",
value: "5"
},
{
key: 6,
text: "Sexta",
value: "6"
},
{
key: 7,
text: "Septima",
value: "7"
}
];
And this is my code:
import React, { Component, useState } from 'react';
import { Dropdown } from 'semantic-ui-react'
import { Select } from 'semantic-ui-react'
import { lista_jugadores } from './jsons/lista_jugadores'
import { categorias_array } from './jsons/categorias'
export default () => {
const[categoria, setCategoria] = useState(categorias_array[0].key);
return(
<div>
<Dropdown placeholder="Seleccionar divisional" options={categorias_array} value={categoria} onChange={ (e) => setCategoria(e.target.value) }/>
<h1>Categoria:{categoria}</h1>
</div>
);
I just want to ensure that in this early stage the state is set visualizing it in h1 but is not working, it remains undefined. Ideally, I would like that my state is directly one of the objects of the array categories, however, I will be able to work if it is just the value.
Thanks in advance.
Upvotes: 1
Views: 78
Reputation: 6766
You have to use the second parameter of the change handler to get the selected id.
Define your handleChange like this,
onChange={ (e, data) => setCategoria(data.value) }
Complete Code:-
const [categoria, setCategoria] = useState(categorias_array[0].key);
const handleChange = (e, data) => {
// data.value will give the selected id
console.log(data.value);
setCategoria(data.value);
};
return (
<div>
<Dropdown
placeholder="Seleccionar divisional"
options={categorias_array}
value={categoria}
onChange={handleChange}
/>
<h1>Categoria:{categoria}</h1>
</div>
);
};
Working Demo - https://codesandbox.io/s/rough-paper-1cvo4?file=/src/App.js:729-1154
Upvotes: 1