Home > Software engineering >  How to add 'checked' to a select item in React?
How to add 'checked' to a select item in React?

Time:05-18

I have two nested map in a select, in the bottom I add the option elements.

return (
    <Modal completion={completion}>
        <InputGroup title="Program" numOfAsterisks={1}>
            <Select formState={formState} setFormState={setFormState} name={'type'}>
                <option value="">- Válassz -</option>
                {Object.entries(programEventTimes ?? {})
                    .sort((a, b) => a[0].localeCompare(b[0]))
                    .map(([key, value]) => (
                        <>
                            {Object.entries(value ?? {})
                                .sort((a, b) => a[0].localeCompare(b[0]))
                                .map(([key2, value2]) => (
                                    <option value="textField" {key == ticket.eventName && key2 == ticket.startTime && 'checked' }>
                                        {key} - {key2}
                                    </option>
                                ))}
                        </>
                    ))}
            </Select>
        </InputGroup>
    </Modal>

Somehow at {key part it says:

'...' expected.

Why whould I use ...?

CodePudding user response:

First of all, it should be selected and not checked Then you condition to have selected as props must be

<option value="textField" selected={key == ticket.eventName && key2 == ticket.startTime}>

Please also note that == is not recommended, and prefer using === to avoid type mistakes

CodePudding user response:

It mean if you want to pass object prop to child you need to use ... syntax like this

<option value="textField" {...{selected: key == ticket.eventName && key2 == ticket.startTime}}>
     {key} - {key2}
</option>

... is spread operator .In react ... will help spread your objectobj={key:value} <span {...obj} /> into this <span key={value}/>

  • Related