简体   繁体   中英

Assigning default value to Autocomplete in MaterialUI and React.js

I would like to display default value to my Autocomplete TextField component from Material UI in React.js. A pre-populated value that is automatically loaded from the users' profile and that can be changed with another one from the list.

Here is my code:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

export const ComboBox =() => {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 },
  { title: 'The Dark Knight', year: 2008 } 
]

I only see the input field with the label on it. defaultValue is listed as an API of both TextField and Autocomplete and I also tried to move it directly under Autocomplete. Still not working.

your defaultValue of <AutoComplete /> should have the same format as your options , the getOptionLable() is used to form the label even from your defaultValue .

in your code title property of the string is undefined , so nothing is shown.

this should work fine:

<Autocomplete
    id="combo-box-demo"
    options={top100Films}
    defaultValue={{ title: "The Godfather", year: 1972 }}
    getOptionLabel={(option) => option.title}
    style={{ width: 300 }}
    renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
/>

You can use the defaultValue option like this:

<Autocomplete
    id="combo-box-demo"
    options={top100Films}
    defaultValue={ top100Films[0] }
    getOptionLabel={(option) => option.title}
    style={{ width: 300 }}
    renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
/>

If you use multiple so you should set defaultValue in list like blow

<Autocomplete multiple id="tags-standard" options={categoryList}
    defaultValue={[{ title: "cat1", id: 1 }, { title: "cat2", id: 2 }]}

    getOptionLabel={(option) => option.title}
    renderInput={(params) => (
    <TextField {...params} variant="standard" label="Category" />
    )}
    onChange={handleCategory}
                            
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM