Hola a todos, tengo una pregunta sobre cómo borrar TextField después de hacer clic en el icono. Gracias
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> ) }} />
Aquí está la solución completa. Hubo un error en la función filterResults
.
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> ); }
Enlace de Codesnadbox: 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> ) }} />
Usuario un estado para mantener el texto. Y use ese valor como valor de textare. Cambie ese estado a vacío dentro de la función clearSearch.