skip to Main Content
stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data

const [selectedNamesState, setSelectedNamesState] = useState([]);

const transformedNpaData = stateNPAValue[formData.state.value].map((label, index) => ({
    label,
    value: index.toString()  // You can use the index as the value or any unique identifier
  }));

<Autocomplete
                multiple
                id="fixed-tags-demo"
                name="Npa"
                value={selectedNamesState}
                onChange={(event, newValue) => {
                  setSelectedNamesState(newValue)
                  NPAHandler(newValue);
                  changeHandleStateErrorRemove(event)
                }}                
                options={transformedNpaData}
                getOptionLabel={(option) => option.label.replace(/[[]']+/g, '')}
                defaultValue={[transformedNpaData[0].label]}
                renderTags={(tagValue, getTagProps) =>
                  tagValue.map((option, index) => (
                    <Chip
                      label={option.label.replace(/[[]']+/g, '')}
                      {...getTagProps({ index })}
                    />
                  ))
                }
                style={{ width: 500 }}
                renderInput={(params) => <TextField {...params} label={formData.state.value} />}
                isOptionEqualToValue={(option, value) => {
                  return option.value === value.value;
                }}
              />

I wanted to select "All" as a default value in multiselect dropdown but defaultValue option is not working. Please let me know what is wrong with this code.

2

Answers


  1. looks like your Autocomplete component and your props are expecting the data type to be like below, and you are giving a correct type to options prop. I think defaultValue should also be the same type

    interface AutocompleteOption {
      label: string;
    }
    

    so I think changing the default value as below will solve the issue.

    // ...
    
    <Autocomplete
        // ...
        defaultValue={[transformedNpaData[0]]}
        // ...
    />
    
    Login or Signup to reply.
  2. You are rendering Autocomplete using controlled input. In such cases, you will have to set the default value in the useState that is controlling the selected values for Autocomplete. Read the doc here. This is what its written in doc:

    defaultValue: The default value. Use when the component is not controlled.

    Considering that the option All will always be on the top of the list. You can initialize selectedNamesState as follows:

    const [selectedNamesState, setSelectedNamesState] = useState([
      {
        label: "All",
        value: "0",
      },
    ]);
    

    Your options array in array of object, in case you are comfortable with converting it into array of string then the solution can be even simpler.

    import { Autocomplete, Chip, TextField } from "@mui/material";
    import { useState } from "react";
    
    const someKey = "someKey";
    const stateNPAValue = {
      [someKey]: ["All", "959", "203", "860", "475"],
    };
    
    function App() {
      const [selectedNamesState, setSelectedNamesState] = useState(["All"]);
    
      const transformedNpaData = stateNPAValue[someKey];
    
      return (
        <div className="App">
          <Autocomplete
            multiple
            id="fixed-tags-demo"
            name="Npa"
            value={selectedNamesState}
            onChange={(event, newValue) => {
              setSelectedNamesState(newValue);
            }}
            options={transformedNpaData}
            getOptionLabel={(option) => {
              return option.replace(/[[]']+/g, "");
            }}
            // defaultValue={[transformedNpaData[0].label]}
            renderTags={(tagValue, getTagProps) =>
              tagValue.map((option, index) => (
                <Chip
                  key={option}
                  label={option.replace(/[[]']+/g, "")}
                  {...getTagProps({ index })}
                />
              ))
            }
            style={{ width: 500 }}
            renderInput={(params) => <TextField {...params} label="test" />}
          />
        </div>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search