Home
Support Forums

Submitting form sends empty inputs

Hello,

I cant seem to figure out what I am doing wrong. I made my site with create react app. I originally had the form working fine. When I finally got it to redirect to a thank you page, the form stopped working.

Here’s the link https://treeservice.netlify.app

import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { TextField, Button, makeStyles } from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
  forms: {
    marginLeft: 50,
    marginRight: 50,
    [theme.breakpoints.up('lg')]: {
      marginLeft: 100,
      marginRight: 50,
    },
  },
}));

const encode = (data) => {
  return Object.keys(data)
    .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
    .join('&');
};

function ContactForm() {
  const classes = useStyles();

  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [address, setAddress] = useState('');
  const [message, setMessage] = useState('');
  const [redirect, setRedirect] = useState(false);

  const handleChange = (e) => {
    if (e.target.name === 'name') {
      setName(e.target.value);
    } else if (e.target.name === 'phone') {
      setPhone(e.target.value);
    } else if (e.target.name === 'address') {
      setAddress(e.target.value);
    } else {
      setMessage(e.target.value);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const dataToSubmit = {
      name,
      phone,
      address,
      message,
    };

    fetch('/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: encode({ 'form-name': 'contact', dataToSubmit }),
    })
      .then(setRedirect(true))
      .catch((error) => alert(error));
  };

  if (redirect) {
    return <Redirect push to={{ pathname: '/success-page' }} />;
  }
  return (
    <form className={classes.forms} onSubmit={handleSubmit}>
      <TextField
        style={{ marginTop: 8, marginBottom: 8 }}
        name='name'
        label='Name'
        required={true}
        type='text'
        value={name}
        onChange={handleChange}
        placeholder=''
        helperText=''
        fullWidth
        margin='normal'
        InputLabelProps={{
          shrink: true,
        }}
        variant='filled'
      />
      <TextField
        style={{ marginTop: 8, marginBottom: 8 }}
        name='phone'
        label='Phone'
        required={true}
        type='text'
        value={phone}
        onChange={handleChange}
        placeholder=''
        helperText=''
        fullWidth
        margin='normal'
        InputLabelProps={{
          shrink: true,
        }}
        variant='filled'
      />
      <TextField
        style={{ marginTop: 8, marginBottom: 8 }}
        name='address'
        label='Address'
        required={true}
        type='text'
        value={address}
        onChange={handleChange}
        placeholder=''
        helperText=''
        fullWidth
        margin='normal'
        InputLabelProps={{
          shrink: true,
        }}
        variant='filled'
      />
      <TextField
        style={{ marginTop: 8, marginBottom: 8 }}
        name='message'
        label='Message'
        required={true}
        type='text'
        value={message}
        onChange={handleChange}
        placeholder='Please describe the work you would like done.'
        helperText=''
        fullWidth
        margin='normal'
        multiline
        InputLabelProps={{
          shrink: true,
        }}
        variant='filled'
      />
      <Button
        variant='contained'
        type='submit'
        style={{
          marginBottom: 30,
          marginTop: 14,
          backgroundColor: 'rgb(18, 93, 55)',
          color: 'white',
        }}
      >
        Send Email
      </Button>
    </form>
  );
}

export default ContactForm;

For some reason the form didn’t paste it its in the code wrapping everything in the return

Have you checked this part of documentation which gives some special instructions on how to integrate Netlify forms in React? https://www.netlify.com/blog/2017/07/20/how-to-integrate-netlifys-form-handling-in-a-react-app/

Hello, Thanks for the reply! I did use the documentation. First I set it up as a stateless form and it worked fine, but the action attribute wouldn’t redirect to my custom success/thank you page. So I tried setting it up using hooks and it does redirect to my custom page and submits and empty form. In the console I can see the state, I just dont know what I’m doing wrong. I followed the Form Handling with a Stateful React Form and only changed parts to use hooks.

Not sure if it will work, but, instead of what you’ve done above, that is, .then(setRedirect(true)), you can use a simple JavaScript, that is .then(window.location.replace('url') and keep your stateful form without the hooks.

Hiya :slight_smile:

Try

body: encode({ 'form-name': 'contact', ...dataToSubmit }),

instead of

body: encode({ 'form-name': 'contact', dataToSubmit }),

Should be fine :slight_smile: Great stuff setting everything else up!


Jon

Thanks Jon! Thats all I needed to get it working correctly