Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda