[Input] How to clear the input value of an Input on a button click?
- Dominant language
- TypeScript
- Stars
- 10.9k
- Forks
- 543
- Avg merge
- 1d 20h
- Merged PRs (30d)
- 101
Description
# Get help
## Ask a question
I'm trying to add a clear button (a floating X icon) to the Input component to clear the input field. The Input component does not have something built-in for this, but I'm struggling with a userland implementation.
If I want to be able to clear the current input, I need to use controlled state instead of uncontrolled. I can't access the underlying `Input` value if it is uncontrolled, which makes sense. This is fine since I already need to control the state to add a character counter. For simplicity of this issue, let's assume I always use controlled state.
The problem is that I don't know how to trigger the `onValueChange` correctly. I want to pass an empty string when the clear button is clicked, but I need to pass `eventDetails` as well. It feels dirty to construct this myself, since this is BaseUI internal logic.
Here's a minimal version of what I have so far.
```tsx
import { Input as BaseInput, type InputProps } from '@base-ui/react/input';
export const Input = (props: InputProps) => {
return (
props.onValueChange('', { /* ? */ })}>X
);
};
```
**Should I write my own custom eventDetails here, or am I approaching this incorrectly?**
---
As a side note, I feel like I'm implementing a lot of functionality in my reusable Input component which could be better solved by BaseUI internally. What my input component supports:
- Showing a affix icon or text (prefix and/or suffix). For this to work, I need to wrap the input in a container that displays the affixes. I am styling the container to look like an input field, and making the real input field invisible. This way it looks like the affix is inside the input. (Position absolute does not work unless I calculate the width to set the correct padding). I have to add a click handler to the wrapper to focus the real input when the affix is clicked. I haven't encountered a headless library yet that solves this.
- Clearing the input, as mentioned in this issue
- Character length display and limiting. I noticed there's an experimental Textarea though with a CharacterCount component, would be nice to have this on the input as well. Additionally, being able to set a hard limit (prevent further input) and a callback when the limit is exceeded (to play a subtle animation on the CharacterCount to grab the user's attention).
- For a password input: a button to show/hide the password. This could remain a userland solution though. I tend to focus the input again after toggling, but I'm not sure if this is the correct approach for a11y.
Contributor guide
Assessment
This issue has not been assessed yet.