Home > Blockchain >  How to clear TextField in react?
How to clear TextField in react?

Time:12-29

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>
        )
      }}
    />

CodePudding user response:

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

CodePudding user response:

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.

  • Related