somniumm
somniumm

Reputation: 115

Display user input value upon submit in react

I want the user to input some text, click submit and the text will be displayed below. I was able to get the input text as a whole, and print it in console. But I don't know how to display the text.

Here's my code: https://codesandbox.io/s/ecstatic-curie-ej6og?file=/src/App.js

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [enteredText, setEnteredText] = useState("");
  const textChangeHandler = (i) => {
    setEnteredText(i.target.value);
    //console.log(i.target.value);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    const x = enteredText;
    console.log(x);
    setEnteredText("");
  };

  return (
    <div className="App">
      <h1>Get user input</h1>
      <form onSubmit={submitHandler}>
      <input
        placeholder="type something"
        type="text"
        value={enteredText}
        onChange={textChangeHandler}
      />
      <button type="submit" >
        Submit
      </button>
      </form>

      <p>You just typed: {x}</p>  // This is wrong. x is out of scope. But i'm not sure how to write this line. 
    </div>
  );
}

Upvotes: 0

Views: 2963

Answers (1)

Houssam
Houssam

Reputation: 1877

You can use an additional state variable to store the "submitted text". You would update that new state variable with the text from the enteredText state variable before emptying it. You could also make sure the "submitted text" has a value before displaying it.

I am including code that does what I described, but you can also try implementing it on your own before looking at it:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [enteredText, setEnteredText] = useState("");
  const [submittedText, setSubmittedText] = useState(null);
  const textChangeHandler = (i) => {
    setEnteredText(i.target.value);
    //console.log(i.target.value);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    setSubmittedText(enteredText);
    setEnteredText("");
  };

  return (
    <div className="App">
      <h1>Get user input</h1>
      <form onSubmit={submitHandler}>
      <input
        placeholder="type something"
        type="text"
        value={enteredText}
        onChange={textChangeHandler}
      />
      <button type="submit" >
        Submit
      </button>
      </form>

      {submittedText && (<p>You just typed: {submittedText}</p>)}
    </div>
  );
}

Upvotes: 2

Related Questions