Woodchuck
Woodchuck

Reputation: 4474

Change SelectInput based on the selection of another one in React-Admin

My React-Admin UI has a create resource that has a SimpleForm with a couple selection boxes.

Those selection boxes, Location and Time Zone, are decorated with ReferenceInput, so as to pull their selectable values from api endpoints:

<Create>
    <SimpleForm>
        ... 
        <ReferenceInput 
            label="Location"
            source="id"
            reference="locations"
        >
            <SelectInput 
                optionText={choice => `${choice.location}, ${choice.state}`} />
        </ReferenceInput>

       <ReferenceInput 
           label="Time Zone"
           source="id"
           reference="timezones"
       >
           <SelectInput optionText="timezonecode" />
       </ReferenceInput>
       ...

The user chooses the values for each before submitting the form.

But is there some way to set up SimpleForm to tie these 2 input selections together?

Specifically, I'd like to have the Time Zone field change accordingly when the user changes the Location selection.

The user should actually be able to override this if they go back and change the Time Zone selection. So this would be a one-way connection in that when Location is changed that should trigger a Time Zone change, but not the other way around.

(The Location database table that creates the Location endpoint does have a timezone_id column that references the timezone table's id column. It's just not clear to me yet how to tie these select boxes together in a React-Admin form.)

Upvotes: 0

Views: 1461

Answers (1)

Fran&#231;ois Zaninotto
Fran&#231;ois Zaninotto

Reputation: 7355

You have to use react-hook-form's useWatch hook, as explained in the react-admin documentation (https://marmelab.com/react-admin/Inputs.html#linking-two-inputs). I suppose you want to use the location as a filter. for the timezone options, so this would give something like that:

const TimeZoneInput = (props) => {
  const location = useWatch({ name: 'id' });
  return (
       <ReferenceInput 
           label="Time Zone"
           source="id"
           reference="timezones"
           filter={{ id }}
       >
           <SelectInput optionText="timezonecode" />
       </ReferenceInput>
);

More info on useWatch in the react-hook-form documentation: https://react-hook-form.com/api/usewatch

Upvotes: 1

Related Questions