1

I am creating a form with some handling functions.

This is my functions that handle the events.

const [name, setUsername] = useState("");
  const [age, setAge] = useState("");

  const handleNameChange = (event) => {
    setUsername(event.target.value);
  };
  const handleAgeChange = (event) => {
    setAge(event.target.value);
  };
  const submitFormHandler = (event) => {
    event.preventDefault();
    console.log(name,age);
  };

I use styled component to style my Form tag. import styled from "styled-components";

const Forms = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  & label {
    font-weight: bold;
    margin: 15px;
  }

  & input {
    width: 40%;
    height: 20px;
    cursor: pointer;
  }

  & button {
    margin: 10px;
  }
`;

This is my form.

<Forms onSubmit={submitFormHandler}>
      <label htmlFor="username">Username</label>
      <input id="username" type="text" onChange={handleNameChange} />

      <label htmlFor="age">Age(Years)</label>
      <input id="age" type="number" onChange={handleAgeChange}/>

      <button type="submit">Add User</button>
</Forms>

I use styled components to style the <Form> tag. So , my problem is after I clicked the submit button, I have error on the onSubmit event handler function where name and age of the user input is not displaying on the browser console.

This is the page

After I clicked the submit button, the values are not displaying on the browser console

Phil
  • 157,677
  • 23
  • 242
  • 245
ClericGame
  • 63
  • 7

1 Answers1

1

Your Forms component is a styled <div>.

Only <form> elements emit a submit event. Use this instead...

const Forms = styled.form`
  etc
`;

You're also missing the value bindings in your <input> elements

<input
  id="username"
  type="text"
  value={name}
  onChange={handleNameChange}
/>

<input
  id="age"
  type="number"
  value={age}
  onChange={handleAgeChange}
/>

See Controlled Components

Phil
  • 157,677
  • 23
  • 242
  • 245