Home > Software design >  using useState to change get the input:text and using onclick to print new <p>
using useState to change get the input:text and using onclick to print new <p>

Time:12-02

i'm a beginner in React and trying to learn useState. and I have difficulties on how to get the value of input and to save the value and print it on button click

const HomePage = () => {
  const [state, setState] = useState({
    Name: "",
    surName: "",
  });

  const handleChange = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value,
    });
  };
  const RenderNameOC = () => {
    return (
        <p>
          Halo {Name} {surName}
        </p>
    
    );
  };

  return (
    <DivContainer>
      <ContainerTitle>
        <p>Exercise 2 - Form</p>
      </ContainerTitle>
      <InputContainer>
        <InputArea>
          <label>Name: </label>
          <input type="text" value={state.Name} onChange={handleChange} />
        </InputArea>
        <InputArea>
          <label>Surname: </label>
          <input type="text" value={state.surName} onChange={handleChange} />
        </InputArea>
        <SubmitButton onClick={RenderNameOC}>Submit</SubmitButton>
      </InputContainer>
    </DivContainer>
  );
};

export default HomePage;

this is my code right now and the error it gave me was 'name' and 'surname' is not defined.

my expected result is that there will be 2 input textbox with for name and surname. and when the button is clicked, it will add a new <p> below it.

CodePudding user response:

Here should be state.Name and state.surName

<p>
      Halo {state.Name} {state.surName}
</p>

And add name in both inputs

  <input
    type="text"
    name="Name"
    value={state.Name}
    onChange={handleChange}
  />

  <label>Surname: </label>
  <input
    type="text"
    name="surName"
    value={state.surName}
    onChange={handleChange}
  />

But no point of returning anything RenderNameOC since onClick is a void function. Just move this template below the submit button

Demo

  • Related