Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React input component state is out of sync

I’ve got a fairly straightforward task which should be working out of the box. But it doesn’t.

Input field with a reset value functionality. When the input has a value and a close icon is clicked, the input value should reset.

The state of isFocused is handled by the onFocus and onBlur props calling setIsFocused and setting the right value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const [inputValue, setInputValue] = useState("");
  const [isFocused, setIsFocused] = useState(false);
  const handleOnClick = () => {
    if (isFocused) {
      setInputValue("");
    }
  };

  const handleOnChange = (e) => {
    setInputValue(e.target.value);
  };

  return (
    <chakra.div className="App" p="20">
      <ChakraProvider>
        <InputGroup>
          <Input
            value={inputValue}
            onChange={handleOnChange}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
          />
          <InputRightElement onClick={handleOnClick}>
            {inputValue.length && isFocused ? <CloseIcon /> : <SearchIcon />}
          </InputRightElement>
        </InputGroup>
      </ChakraProvider>
    </chakra.div>
  );

Code is here:
https://codesandbox.io/s/hardcore-shtern-1m5vo0?file=/src/App.js

Close icon is visible when the input is is focused. However, when handleOnClick is fired isFocused value is not what I expect. Hence, the value never gets reset.

>Solution :

Change onClick to onMouseDown.
Check out this answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading