zoukankan      html  css  js  c++  java
  • [React] Validate React Forms with Formik and Yup

    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'));
  • 相关阅读:
    skill:极角排序
    skill:树的重心
    [CF1091F](New Year and the Mallard Expedition)
    2018九省联考(SHOI2018)
    陷入僵局?
    2333
    雨后天晴
    听说我首次抢到食堂最早的馄饨
    难题做不动
    成绩出来了?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10644305.html
Copyright © 2011-2022 走看看