0

I am trying to console log the two fields from my sign up page. However, the item appears in the console for about a second and then disappears. Any help is appreciated. Please find my code for the sign up below

  export default function SignUp() {
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");

  let sign = () => {
    console.log(firstName);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign up
        </Typography>
        <form className={classes.form} noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <TextField
                autoComplete="fname"
                name="firstName"
                id="firstName"
                label="First Name"
                autoFocus
                onChange={(event) => setFirstName(event.target.value)}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                id="lastName"
                label="Last Name"
                name="lastName"
                autoComplete="lname"
                onChange={(event) => setLastName(event.target.value)}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            className={classes.submit}
            onClick={sign}
          >
            Sign Up
          </Button>

1 Answers1

2

The problem is that you are submitting the form without preventing the default (refreshing the page). Make sure you're passing your sign function to the form's onSubmit prop, and then make sure your sign is something along these lines:

let sign = (event) => {
    event.preventDefault();
    console.log(firstName);
};
Pedro Filipe
  • 995
  • 1
  • 8
  • 17
  • Thank you, that worked it appears in the console now. Since there are two fields, can you advise how I can make an object out of them or should I make a new ques for that – new_hello_world May 26 '20 at 17:05
  • @new_hello_world to manage a [state object](https://stackoverflow.com/q/55342406/1218980). – Emile Bergeron May 26 '20 at 17:07
  • 1
    Please mark the answer as the accepted answer if it answers you question. Check @EmileBergeron comment for creating the object :) – Pedro Filipe May 26 '20 at 17:09