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

Update State in React Hooks on Change method

I am wondering why React is not updating the state after a method onChange is called.

Summary: A simple input element with two float-right icons to display. One icon to display if the length of the input text is 0 while the other if the input text length > 0. But it seems React is updating the state after I enter the second text in my input element.

What I need is:

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

Display % if length == 0 and display X is length is > 0.

And if the length > 0 then user on click of X set the input text == "" OR input.length = 0.

Problem is: Though I am able to clear the input but the icon % is not displayed.

enter image description here

export default function App() {
  const [userInput, setUserInput] = useState("");
  const [displayIcons, setDisplayIcon] = useState({
    default: "d-block",
    clear: "d-none"
  });

  const onChange = (e: any) => {
    const _userInput = e.currentTarget.value;
    setUserInput(_userInput);
    console.log("_userInput", _userInput.length);
    console.log("userInput", userInput.length);
    if (_userInput.length > 0)
      setDisplayIcon({ default: "d-none", clear: "d-block" });
    else setDisplayIcon({ default: "d-block", clear: "d-none" });
  };

  const clearText = (e: any) => {
    setUserInput("");
  };

  return (
    <Row>
      <Col>
        <div className="input-group position-relative">
          <div className="form-control">
            <label id="default" className={`${displayIcons.default}`}>
              %
            </label>
            <label className={`${displayIcons.clear}`} onClick={clearText}>
              X
            </label>
            <Input
              type="text"
              className="custom-input"
              placeholder="Enter Something"
              onChange={onChange}
              value={userInput}
            />
          </div>
        </div>
      </Col>
    </Row>
  );
}

>Solution :

Add setting display icon state:

const clearText = (e: any) => {
    setUserInput("");
    setDisplayIcon({ default: "d-block", clear: "d-none" });
};
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