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

Only displaying input value after button click in React

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.

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

>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.

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