码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Validate React Forms with Formik and Yup

时间:2019-04-02 18:34:33      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:document   roc   proc   erro   color   field   shape   int   and   

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‘));

 

[React] Validate React Forms with Formik and Yup

标签:document   roc   proc   erro   color   field   shape   int   and   

原文地址:https://www.cnblogs.com/Answer1215/p/10644305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!