简体   繁体   中英

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

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

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.

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