{}

Submit JSON with React

There are a million ways to handle a form submission with React.

For this example we went with formik and yup.

Here's how to integrate the Submit JSON JS Client with React:


Set up your React project

  1. To get started, make sure you have a working React project. If you do not, follow these instructions.
  2. Then install submitjson along with formik and yup.
npm i submitjson react formik yup # OR pnpm add OR yarn add
shell

Integrate Submit JSON with React

Next create your contact form component and initialize the Submit JSON JS Client.

import SubmitJSON from 'submitjson'
import React from 'react'
import { Field, Form, Formik } from 'formik'
import * as Yup from 'yup'

// Define form validation schema with yup
const schema = yup.object({
  name: yup.string().required(),
  email: yup.string().email().required(),
  message: yup.string().required(),
})

// Initialize a new Submit JSON client
const sj = new SubmitJSON({ apiKey: 'sjk_xxx', endpoint: 'XxXx' })

export const ReactExample = () => (
  <div>
    <h1>Contact Form</h1>
    <Formik
      initialValues={{
        name: 'Yo Yoerson',
        email: '[email protected]',
        message: 'Yo',
      }}
      validationSchema={schema}
      onSubmit={async (values) => {
        // same shape as initial values
        console.log(values)
        // ⚡️ submit data to your endpoint
        const submission = await sj.submit(values)
        console.log('submission:', submission)
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="name" />
          {errors.name && touched.name
            ? <div>{errors.name}</div>
            : null}

          <Field name="email" type="email" />
          {errors.email && touched.email
            ? <div>{errors.email}</div>
            : null}

          <Field name="message" />
          {errors.message && touched.message
            ? <div>{errors.message}</div>
            : null}

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
)
tsx

🚛✨💚 Nice job, you successfully integrated Submit JSON with React.