Bridler Shoc
Bridler Shoc

Reputation: 117

Material UI free solo Autocomplete, how to submit data?

I am new to Material UI and I wonder how it is possible to submit data with a free solo autocomplete component, also with a TextField. My goal is ultimately to push the router to a new page, after the search result.

I think that the code sandbox shows a more clear example:

Code Sandbox

Upvotes: 1

Views: 2408

Answers (1)

Domino987
Domino987

Reputation: 8774

You can just use the onChange of the autocomplete instead of tracking it with a onChange of the textfield:

export default function App() {

  function handleSubmit(event, value) {
    event.preventDefault();
    console.log("Country:", value);
  }

  return (
    <div className="App">
      <h1>Material AutoComplete</h1>
      <h2>How to get this to submit?</h2>

      <div>
        <Autocomplete
          freeSolo
          id="autocomplete"
          disableClearable
          options={allCountries.map((option) => option.countryname)}
          onChange={handleSubmit} // This will be called on selection of the country
          renderInput={(params) => (
            <TextField
              {...params}
              margin="normal"
              aria-label="enter search"
              name="search"
              placeholder="Search"
               // No need to check the onChange here
              InputProps={{
                ...params.InputProps,
                startAdornment: <SearchIcon />,
                type: "search"
              }}
            />
          )}
        />
      </div>
    </div>
  );
}

Upvotes: 3

Related Questions