user15404864
user15404864

Reputation:

How to clear TextField in react?

Hi everyone i have a question regarding on how to clear TextField after clicking the icon? thanks

const [filteredLocations, setFilteredLocations] = useState(locations);

const clearSearch = () => {
    // i dont know what should i put here TextField.clear() or so what ever
  };
  const filterResults = (e) => {
    ....
    setFilteredLocations(filteredLocations);
  };

    <TextField
      placeholder="Search Locations"
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />

Upvotes: 2

Views: 900

Answers (2)

Kasun Jalitha
Kasun Jalitha

Reputation: 771

const [filteredLocations, setFilteredLocations] = useState(locations);

const clearSearch = () => {
  setFilteredLocations("");
  };
  const filterResults = (e) => {
    ....
    setFilteredLocations(filteredLocations);
  };

    <TextField
      value = {filteredLocations}
      placeholder="Search Locations"
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />

User a state to keep the text. And use that value as textare value. Change that state to empty inside clearSearch function.

Upvotes: 2

moshfiqrony
moshfiqrony

Reputation: 4733

Here is the whole solve. There was an error in the filterResults function.

import {useState} from 'react'
import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton";
import ClearIcon from '@mui/icons-material/ClearOutlined'

export default function App() {
  const [filteredLocations, setFilteredLocations] = useState('');

const clearSearch = () => {
    setFilteredLocations('')
  };
  const filterResults = (e) => {
    setFilteredLocations(e.target.value);
  };

    
  return (
    <div className="App">
      <TextField
      placeholder="Search Locations"
      value={filteredLocations}
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />
    </div>
  );
}

Codesnadbox link - https://codesandbox.io/s/how-to-clear-textfield-in-react-tb73t

Upvotes: 2

Related Questions