The "nam" is not getting updated on clicking the button. It is showing blank space after "Hello" after the click

Viewed 20
import React , {useState} from "react";
import ReactDOM from 'react-dom';


const App = () => {
    
    const [disp,setDisp] = useState(1);
    let nam;

    function prin() {
        setDisp(nam);
    }            




    return(

        <>
        <h1>Hello  {disp}</h1>
        <input type="text" placeholder="Enter Your Name" value={nam}/>
        <button onClick={prin}> Click Me !</button>
        

        </>
    )

};
export default App;

There's some problem with the prin() function. I am a beginner trying to learn ReactJS Hooks. Please help me with the bug in the code and the concepts involved here. The goal of the program is to display the name after "Hello" after the button is clicked.

1 Answers

nam is undefined and it won't change.

All you have to do is create two state and then update the value that you want to show in h1 using button click as:

CODESANDBOX LINK

const App = () => {
  const [disp, setDisp] = useState("");
  const [inputValue, setInputValue] = useState("");

  function onChangeInput(e) {
    setDisp(e.target.value);
  }

  function prin() {
    setInputValue(disp);
    setDisp("");
  }

  return (
    <>
      <h1>Hello {inputValue}</h1>
      <input
        type="text"
        placeholder="Enter Your Name"
        value={disp}
        onChange={onChangeInput}
      />
      <button onClick={prin}> Click Me !</button>
    </>
  );
};
Related