I am trying to create a simple React form that, on button click, will display the entered input value in a controlled input element. Specifically, I do NOT want to have an identical solution to that in the React docs (constantly updating the displayed value on input change), rather I only want it to update the displayed paragraph text after the user has hit the submit button. I am able to do this with this current solution (conditionally rendering based on submitted state that is set in handler functions):
import { useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [submitted, setSubmitted] = useState(false);
const handleSubmit = e => {
e.preventDefault();
setSubmitted(true);
};
const handleChange = e => {
setSubmitted(false);
setText(e.target.value);
};
return (
<>
<form onSubmit={e => handleSubmit(e)}>
<label>Text: </label>
<input type="text" value={text} onChange={e => handleChange(e)} />
<button type="submit" onClick={handleSubmit}>
Show
</button>
{submitted && <p>{text}</p>}
</form>
</>
);
}
But I am guessing that there is a much better way to do this.
>Solution :
If you want to be able to submit multiple times and keep the last before submitting again, use this:
import { useState } from 'react';
export default function App() {
const [text, setText] = useState('');
const [displayText, setDisplayText] = useState('');
const handleSubmit = e => {
e.preventDefault();
setDisplayText(text);
};
const handleChange = e => {
setSubmitted(false);
setText(e.target.value);
};
return (
<>
<form onSubmit={e => handleSubmit(e)}>
<label>Text: </label>
<input type="text" value={text} onChange={e => handleChange(e)} />
<button type="submit" onClick={handleSubmit}>
Show
</button>
{displayText && <p>{displayText}</p>}
</form>
</>
);
}
displayText && ... is so that the paragraph tag doesn’t exist until it has a value to display, but you can just replace that section with out that and it will work.