'How to update a form's input text state immediately in React using setState()
const [text, setText] = useState('');
const handleTextChange = (e) => {
setText(e.target.value);
}
// Inside a form
<input onChange={handleTextChange} value={text} type="text" />
I'm trying to do something very simple but can't quite get it to work properly. From the code above, I have text and setText to store and update the state, and a function handleTextChange which gets called by the input field's onChange method.
I know that setState() is async so wont update immediately, however, If i need access to the updated result immediately how can I get it? I've read that useEffect hook can be used to do this but I can't figure out how I need to use it. If there is another way to accomplish this then please share.
The main objective is to get the "updated value of the text state variable" as the user is typing in the input field.
Solution 1:[1]
you can use e.target.value
for the latest value unless you really want to use a state variable then you can wrap it up in useEffect
but there does not seem to be a need for it :)
you can just use disabled={text.length===10}
Solution 2:[2]
I don't think useEffect
is appropriate for what you are trying to do
function App({ onSubmit }) {
const [text, setText] = React.useState("")
return <form onSubmit={e => onSubmit(text)}>
<input
onChange={e => setText(e.target.value)}
value={text}
placeholder="enter a comment"
/>
<button
type="submit"
disabled={text.length >= 10}
children="disabled at 10 chars"
/>
<p>{Math.max(0, 10 - text.length)} characters remaining...</p>
</form>
}
ReactDOM.render(<App onSubmit={alert} />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |