Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
Get key from datalist in Form.Control

I get from the API a json, with a list of each staff member:


const MOCK_STAFF = [{
    id: 1,
    name: "Jhon Doe",
    department: "HR"
}, {
    id: 2,
    name: "Jane Doe",
    department: "Research"
}, etc

Then they get mapped in a datalist <option>, inside a Form.Control component:

                    <Form.Group className="mb-3">
                        <Form.Label>Name</Form.Label>    
                            <Form.Control
                            name='staffName'
                            value={0}
                            list="namesList"
                            onChange={(e) => onChangeHandler(e)}/>
                        <Form.Label>Department</Form.Label>
                            <Form.Control disabled
                            name=department
                            value={}    
                            />   
                
                        <datalist id="namesList">
                           {MOCK_DATA.map( (data) => (
                            <option key={data.id} value={data.department}>{data.name}</option>
                           ))}
                        </datalist>
                    </Form.Group>

sandbox link: https://codesandbox.io/s/modal-t59e7z?file=/src/App.tsx

I would like the onChange={(e) => onChangeHandler(e)} to get the data-value of <option key={data.id} on form submit, and to make the department Form.Control to reference the value of <option value={data.department} in the datalist. The 'key' id must not show to the user, it is used as a primary key on the database.

I have tried:

function onChangeHandler(e:React.SyntheticEvent) {
    
    console.log(e.target.key);
}

but "property key does not exist on event.target". Nor I can use document.getElementById(); with react. How can I get the values 'key', 'value' and/or 'default-value` from a Form.Control with a datalist?

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I could not achieve this with data-list, but did so with react-select:

type StaffOption = {
    label: string, value: number
}
const MOCK_DATA= [{
    id: 1,
    name: "Jhon Doe",
    department: "HR"
}, {
    id: 2,
    name: "Jane Doe",
    department: "Research"
}, {
    id: 3,
    name: "Elizabeth meyer",
    department: "Operations"
}]

type NameOption = {value: number, label: string, department: string}
type NameOptions = Array<NameOption>

function AddNewRowModal(props:AddNewRowProps) {
    const [selectedStaffID, setSelectedStaffID] = useState(0);

    function onChangeHandler(option: OnChangeValue<StaffOption, false>, 
             actionMeta: ActionMeta<StaffOption>) {
        console.log(option);  //this returns all 3 values defined on type StaffOption
        if (option?.value !== undefined) {
            setSelectedStaffID(option.value!);
        }  
    }

    function BuildOptions (data:any[]) {
        var options:NameOptions = []
        data.forEach(element => {
            options.push({
            value: element.id!,
            label: (element.name),
            department: element.department});
        });
        return options;
   var nameOptions = BuildOptions(MOCK_DATA);
    return (
        <Modal
            show={props.showModal}
            backdrop="static"
            keyboard={false}
            onHide={() => props.closeModal()} >
                <Modal.Header closeButton>
                    <Modal.Title>Add new Entry</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                   <Select 
                    options={nameOptions}
                    onChange={onChangeHandler} />
                </Modal.Body>
                <ModalFooter>
                    <Button variant='primary'>Create Entry</Button>
                    <Button variant='danger' onClick={() => props.closeModal()}>Cancel</Button>
                </ModalFooter>
            </Modal>
    );
}

And the codesandbox

about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda