Clear input text on button click

Viewed 278

I have three components.

  1. SearchBarInput which is a controlled component based on Material UI OutlinedInput. As props it takes onClickClear.
  2. Input which renders the SearchBarInput and passes to it the onClickClear
  3. App which renders the Input component and passes to it a handleClickClear function.

Code: https://codesandbox.io/s/amazing-allen-fprpd

When the user inputs anything in the Input, an X icon appears. If the user clicks it, it sets the state of the input to undefined. Thus, the state is correctly cleared. However, it does not clear the UI of the input from what the user has typed.

What I am trying to achieve is a similar behaviour of <input type="search"> in plain html

See:

Visual Explanation

3 Answers

I updated your code in this sandbox. I ended up passing inputText down as a prop (added it to the necessary interfaces) and used that as value for the input. You also need to make inputText an empty string when you hit the clear icon. If it's undefined it doesn't update the input component. See below.

App.tsx

...

 const handleClickClear = () => {
    setInputText("");
  };

  return (
    <div className="App">
      <Input
        showClearIcon={!!inputText}
        onSearchBarChange={(event) => handleSearchBarChange(event)}
        onClickClear={handleClickClear}
        inputText={inputText}
      />
      <br />
      <p>My text: {inputText} </p>
    </div>

Then in the child components declare inputText as a prop in the interfaces and pass the prop down to the child components.


interface Props {
  ...
  inputText: string | undefined;
  ...
}

Finally, add it as the value passed to OutlinedInput in SearchBarInput.

SearchBarInput.tsx

  <OutlinedInput
      type="text"
      value={inputText}
      onChange={onChange}
   ...
   />

It's just about this function over here:

const handleClickClear = () => {
    setInputText(undefiend);
  };

in App.tsx you need to replace it with this one over here

const handleClickClear = () => {
    setInputText("");
  };

and we have also passed down the textInput value from the App.tsc all the way down to SearchBarInput.tsx and add it as a value to the input it self

and you can find my solution here: https://codesandbox.io/s/cranky-payne-2727u?file=/src/App.tsx:377-436

first, be sure to set your inputText to be string type only. if you set to be also undefined you will face error A component is changing a controlled input to be uncontrolled if it's value becomes undefined.

in this way your setState should be:

const handleClickClear = () => {
    setInputText("");
  };

second, you need to pass down inputText as prop to Input then to SeachInput. and remember to also set value prop type to be string.

passing to Input

  <Input
    value={inputText}
    // other props

passing to SearchInput

<SearchBarInput
  value={value}
  // other props

now SearchBarInput will have value updated accordingly.

Related