material ui react form example

Example 1: Simple form based react material ui

import React from 'react'
import { Field, reduxForm } from 'redux-form'
import TextField from '@material-ui/core/TextField'
import Checkbox from '@material-ui/core/Checkbox'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import FormControl from '@material-ui/core/FormControl'
import Select from '@material-ui/core/Select'
import InputLabel from '@material-ui/core/InputLabel'
import FormHelperText from '@material-ui/core/FormHelperText'
import Radio from '@material-ui/core/Radio'
import RadioGroup from '@material-ui/core/RadioGroup'
import asyncValidate from './asyncValidate'

const validate = values => {
  const errors = {}
  const requiredFields = [
    'firstName',
    'lastName',
    'email',
    'favoriteColor',
    'notes'
  ]
  requiredFields.forEach(field => {
    if (!values[field]) {
      errors[field] = 'Required'
    }
  })
  if (
    values.email &&
    !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
  ) {
    errors.email = 'Invalid email address'
  }
  return errors
}

const renderTextField = ({
  label,
  input,
  meta: { touched, invalid, error },
  ...custom
}) => (
  
)

const renderCheckbox = ({ input, label }) => (
  
} label={label} />
) const radioButton = ({ input, ...rest }) => ( } label="Female" /> } label="Male" /> } label="Other" /> ) const renderFromHelper = ({ touched, error }) => { if (!(touched && error)) { return } else { return {touched && error} } } const renderSelectField = ({ input, label, meta: { touched, error }, children, ...custom }) => ( Age {renderFromHelper({ touched, error })} ) const MaterialUiForm = props => { const { handleSubmit, pristine, reset, submitting, classes } = props return (
) } export default reduxForm({ form: 'MaterialUiForm', // a unique identifier for this form validate, asyncValidate })(MaterialUiForm)

Example 2: Simple form based react material ui

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const asyncValidate = (values /*, dispatch */) => {
  return sleep(1000).then(() => {
    // simulate server latency
    if (['[email protected]', '[email protected]'].includes(values.email)) {
      // eslint-disable-next-line no-throw-literal
      throw { email: 'Email already Exists' }
    }
  })
}

export default asyncValidate

Tags:

Misc Example