1

I'm pretty new to React & JavaScript in general, and could use some help with a fairly simple thing:

I want to output the input value from my text <input> into my <h4> by hitting the update button. (Or something similar if that doesn't work)

return (
        <div>
            <div className="top-menu">
                <div>
                    <h1>Progress</h1>
                </div>
            </div>

            <div className="progress-container">
                <h4>Progress: 43 %</h4>
                <div className="progress-bar"></div>
            </div>

            <div className="inputs">
                <label>Progress (in %)</label>
                <div className="input">
                    <form>
                        <input id="progress" type="text" placeholder="e.g. 75" />
                        <button className="button">Update</button>
                    </form>
                </div>
            </div>
        </div>
    );

Thanks so much for your help!

2
  • The best way to do this is to control the value of the input in you component's state by setting props value and onChange on the input element. Read up on making a "controlled input". Commented Oct 25, 2020 at 22:43
  • Actually I like Drew's answer better since you said that you only want to update after pressing the button. Commented Oct 25, 2020 at 22:47

1 Answer 1

3

Create some progress state and use the form's onSubmit callback to update state and clear the input value. Render the progress state into the h4 tag.

function App() {
  const [progress, setProgress] = useState(43); // <-- progress state

  return (
    <div>
      <div className="top-menu">
        <div>
          <h1>Progress</h1>
        </div>
      </div>

      <div className="progress-container">
        <h4>Progress: {progress} %</h4> // <-- render progress state
        <div className="progress-bar"></div>
      </div>

      <div className="inputs">
        <label>Progress (in %)</label>
        <div className="input">
          <form onSubmit={e => { // <-- form submit callback
            e.preventDefault(); // prevent default form action so page doesn't reload
            const { value } = e.target.progress;
            setProgress(value); // update state
            e.target.progress.value = ''; // reset input value
          }}>
            <input id="progress" type="text" placeholder="e.g. 75"></input>
            <button type="submit" className="button">Update</button> // <-- type = submit
          </form>
        </div>
      </div>
    </div>
  );
}

Edit react-get-value-of-inputtype-text-and-output-the-value

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.