[React] Validate React Forms with Formik and Yup

霸气de小男生 提交于 2020-02-26 09:17:08

Validating forms in React can take several lines of code to build. However, Formik's ErrorMessage component and Yup simplify that process.

 

import { ErrorMessage, Field, Form, Formik } from 'formik';
import React from 'react';
import { render } from 'react-dom';
import './index.css';
import ItemList from './ItemList';
import * as Yup from 'yup';

const initialValues = {
  item: '',
};

const validationSchema = Yup.object().shape({
  item: Yup.string().required('Item name is required'),
});

const App = () => {
  const [items, setItems] = React.useState([]);

  return (
    <React.Fragment>
      <h2>Regular Maintenance:</h2>
      <ItemList items={items} />
      <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={values => {
          setItems([...items, values.item]);
        }}
      >
        <Form>
          <label htmlFor="item">Item:</label>
          <Field type="text" name="item" />
          <ErrorMessage name="item" />
          <button type="submit">Add Item</button>
        </Form>
      </Formik>
    </React.Fragment>
  );
};

export default App;

render(<App />, document.getElementById('root'));

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!