Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!