Clear an Input Field With Reactjs

Clear input field using React hooks

You're using an uncontrolled input. Try setting value={message} on the input.

How to clear input field after clicking submit in react js redux

Try this way:

clearInput = () => {
const reminder = { ...this.state.reminder, title: '' };
this.setState({ reminder });
};

handleSubmit = (e) => {
e.preventDefault();
this.props.dispatch(addRemainder(this.state.reminder));
this.clearInput();
};

Clear input field reset back to defaultValue (0)

I am assuming you are using Material UI's TextField component. As stated in the documentation, default value is only displayed when your component is uncontrolled. Here you have a controlled component.

https://mui.com/material-ui/api/text-field/

What you can do is providing onChange a function check whether e.target.value is empty ("") or not, so you can set your variable to 0 or e.target.value.

handleChange = (e) => {
if (e.target.value === "" && mynumber !== 0) {
setMyNumber(0)
} else {
setMyNumber(e.target.value)
}
}
<TextField
onChange={handleChange}
/>

clear text-field after submit in react

x clear icon appears only when the input has value - react

You can conditional render the icon based on the value of the input field. Maintain a state for the value using the useState hook. onChange will trigger everytime you enter a value into the input field and set the state.

export default function Search() {
const inputElt = useRef(null);
const [value,setValue] = useState('')

return (
<form className='flex'>
<input
ref={inputElt}
className='flex-grow focus:outline-none cursor-pointer'
type='search'
value={value}
onChange={(e) =>setValue(e.target.value)}
/>
{value && <XIcon className='h-5' />}
)
}


Related Topics



Leave a reply



Submit