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:
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.
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" });
};
