Home > Software engineering >  Getting undefined instead of Input Field value
Getting undefined instead of Input Field value

Time:12-10

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

function App() {
  const [InputVal, setInputVal] = useState();
  const [ShowDiv, setShowDiv] = useState(
    <div>
      <p>Hello world. This is default "Show Div" value</p>
    </div>
  );

  const ChangeDivFunc = () => {
    setShowDiv(
      <div>
        <p style={{ color: "red" }}>
          Hello World. This is updated "Show Div" value
        </p>
        <input onChange={getInputval} type="text" />
        <br />
        <br />
        <button onClick={AlertVal}>Show Input Value</button>
      </div>
    );
  };

  const getInputval = (val) => {
    setInputVal(val.target.value);
  };

  const AlertVal = () => {
    alert(InputVal);
  };

  return (
    <div className="App">
      <h1>Example</h1>
      <br />
      <button onClick={ChangeDivFunc}>Change Div</button>
      {ShowDiv}
    </div>
  );
}

export default App;

Code Flow:

  1. Click Change Div button then it will show Input field and Show Input Value button.
  2. Now, Enter some value in input field and click the Show Input Value button to get the value of input field.

Problem: It returns undefined instead of input field value.

I'm trying to get the value of Input field when Show Input Value button is clicked. But I'm not getting the desired results.

Here's the Sandbox link : Click for Code

CodePudding user response:

Do not store html node inside state. You can simply store only a boolean value to switch between what node to show. I'm not pretty sure but it may cause weird behavior since React internally depends heavily on the DOM/HTML UI Tree (see Managing State).

Try this instead:

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

function App() {
  const [inputVal, setInputVal] = useState("");  // initialize as empty string.
  const [showDiv, setShowDiv] = useState(false);

  const changeDivFunc = () => {
    setShowDiv(true);
  };

  const getInputVal = (event) => {  // The arg is Event object, not val
    setInputVal(event.target.value);
  };

  const alertVal = () => {
    alert(inputVal);
  };

  return (
    <div className="App">
      <h1>Example</h1>
      <br />
      <button onClick={changeDivFunc}>Change Div</button>
      {
        showDiv? (
          <div>
            <p style={{ color: "red" }}>
               Hello World. This is updated "Show Div" value
            </p>
            <input value={inputVal} onChange={getInputVal} type="text" />
            <br />
            <br />
            <button onClick={alertVal}>Show Input Value</button>
          </div>
        ) : (
          <div>
            <p>Hello world. This is default "Show Div" value</p>
          </div>
        )
      }
    </div>
  );
}

export default App;

Forked Codepen

  • Related