0
votes

As I understood, in react-select (latest) you need to send an object to the value props, to select/preselect an option. I am also using react-hook-form for my form management.

Is it possible to set the value through react-select or do I need to use react-hook-form's setValue()

As I click on an Item, I send this to my states:

const handleSectionOnClick = (id) => {
    setTravelRoute({
        'LocationEnd': { value: +travelRoutes[id].LocationIdEnd, label: travelRoutes[id].LocationCityEnd },
        'LocationStart': { value: +travelRoutes[id].LocationIdStart, label: travelRoutes[id].LocationCityStart },
        'startDate': new Date(),
        'endDate': new Date()
    })
}  

My Demo object looks like this:

    {
        'LocationCityEnd': "Berlin, Ger",
        'LocationCityStart': "Hattingen, Ger",
        'LocationIdEnd': 2,
        'LocationIdStart': 1,
        'startDate': new Date(),
        'endDate': new Date()
    }  

My (LocationStart) select component looks like this:

<Controller
render={({ onChange }) => (
    <Select
        styles={customStyles}
        onChange={handleOnChangeStartLocation}
        name="startLocation"
        value={travelRoute?.LocationStart}
        options={selectOptions}
        placeholder="Choose..."

    />
)}
name="startLocation"
className={`${errors.startLocation ? 'inputSelectError' : ''}`}
control={control}
rules={{ required: true }}
/>  

Nothing gets selected, not even the value/label.
What Am I missing? Thank you!

EDIT:

I added the handleOnChangeStartLocation function:

const handleOnChangeStartLocation = e => {
    const { value, label } = e;
    setTravelRoute(prevState => ({
        ...prevState,
        LocationIdStart: value,
        LocationCityStart: label
    }))
}
1
What about handleOnChangeStartLocation?Emanuele Scarabattoli
I added the functionMarek123

1 Answers

0
votes

The problem seems to be that you are not updating LocationStart with the new value/label. You should do something like:

const handleOnChangeStartLocation = e => {
    const { value, label } = e;
    setTravelRoute(prevState => ({
        ...prevState,
        LocationStart: e, // add this line of code
        LocationIdStart: value,
        LocationCityStart: label
    }))
}