skip to Main Content

I have a React/Typescript project that I am working on. I have an Autocomplete element whose options are a series of object that contain {label, value, and endOfDay}. I have the option labels displaying correctly in the dropdown, however, when an option is selected, in the input field, I want to display the value of the option, not the label.

To be more specific, the label could be "01/01/2024" but the value is "01/01/2024 00:00". I want the value to be displayed when they select the label "01/01/2024". Eventually, I want it to display the value + endOfDay, but my current problem is getting the value to display instead of the label.

Here is my Autocomplete code:

{!endPickerAvailable && (
        <Box sx={pickerBoxStyle(theme)}>
          <Typography sx={labelStyle(theme)}>TIME RANGE</Typography>
          <Box sx={accentAndPickerStyle(theme)}>
            <StyledHUDAccent sx={HUDAccentStyle(theme)} />
            <Autocomplete
              data-testid='database-picker'
              options={formatTimeRangePickerDates(startValueOptions)}
              getOptionLabel={(option) => option.label}
              renderInput={(params) => (
                <TextField {...params} value={selectedDate.value} />
              )}
              onChange={(event, selectedOption) => {
                if (selectedOption) {
                  setSelectedDate(selectedOption);
                  console.log(selectedDate);
                }
              }}
              sx={databasePickerStyle(theme)}
              disableClearable
            />
          </Box>
        </Box>
      )}

selectedDate is being set correctly and the value is the correct thing to display

I tried setting the value of TextField to be the value that I want displayed but it is still displaying the label on selection instead of the value of the option. I have also tried using renderOption, but haven’t been able to get that to work either.

2

Answers


  1. Chosen as BEST ANSWER

    Got it? Literally did the opposite of what I thought I had to do and it worked the way I want it to. Still very confused as to why this works:

      renderOption={(props, option) => (
                    <li {...props}>{option.label}</li>
                  )}
                  getOptionLabel={(option) => option.value}


  2. The TextField value does not affect what is shown in the input

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search