Home > Software engineering >  React input component state is out of sync
React input component state is out of sync

Time:07-09

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.

  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.

CodePudding user response:

Change onClick to onMouseDown. Check out this answer.

  • Related