Search code examples
reactjstypescriptjsxreact-typescripttsx

Conditionally add attribute that requires an array


I'm using Material UI's 'Autocomplete' and it has this attribute defaultValue to specify the preselected items in a multiple choice combo box.

This is the code I have:

{showDTPicker &&
 <Autocomplete
  multiple
  onChange={(_, newValues) => {
   setSelectedDatatables(newValues)
  }}
  id="combo-box-tables"
  options={datatables}
  defaultValue={selectedDatatables}
  getOptionLabel={(option) => option?.name}
  getOptionSelected={(option, value) => option?.name === value?.name}
  style={{width: 300, marginRight: '10px'}}
  renderInput={(params) => <TextField {...params} label="Select datatable" variant="outlined"/>}
 />
}

This is a box used to update some fields, so it has to read the current fields (selectedDatatables) and then update the state (setSelectedDatables) to save them.

Sometimes, though, some of the objects don't have any field set and so selectedDatatables is null. This breaks the component as the defaultValue attribute expects an array of something.

How can I use this attribute only when selectedDatatable is not null?

The project is in TS/TSX, and selectedDatatables is an array and its elements are of type datatable (which is then an object with other fields like name and content).

The showDTPicker is a state value that shows the component when is set.


Solution

  • You can pass the prop as :

    defaultValue={selectedDatatables || []}