question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Form.create new API discussion: Render Props or React Hooks

See original GitHub issue
  • I have searched the issues of this repository and believe that this is not a duplicate.

What problem does this feature solve?

In order to avoid to wrap a component with Form.create(), it could be nicer to be able to define it in a declarative way.

What does the proposed API look like?

const SomeComponent = () => (
  ...
  <Form.Create {...options}>
    {({getFieldDecorator, ...}) => (
      <Form onSubmit={...}>
        {...}
      </Form>
    )}
  </Form.Create>
  ...
)

Currently I use:

const FormCreate = Form.create()(
  ({ form, children }: { form: WrappedFormUtils; children(form: WrappedFormUtils): React.ReactElement<any> }) =>
    children(form),
);

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:9
  • Comments:23 (13 by maintainers)

github_iconTop GitHub Comments

22reactions
afc163commented, Dec 23, 2018

React hooks may be next API solution instead render props: https://github.com/ant-design/ant-design/issues/12857#issuecomment-433777455


from @yesmeck

const { useForm } = Form;
const LoginForm = () => {
  const handleValuesChange = () => console.log('Value changes'). 
  const form = useform({
    onValuesChange: handleValuesChange,
  });
  const { getFieldDecorator, validateFields } = form;
  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }
  return (
    <Form onSubmit={handleSubmit}>
      <FormItem>
        {getFieldDecorator('userName')(<Input placeholder="Username" />)}
      </FormItem>
    </Form>
  );
};
13reactions
jas0ncncommented, May 9, 2019

It’s there any progress in this proposal? @afc163 Here is the way I use Ant Design Form component with React Hooks

import React from 'react'
import { Modal, Form, Input, Radio, InputNumber, message } from 'antd'
import { useForm } from '@lib/hooks'

export function CreateSomething () {
    const { form, useFormItem, input, radio, inputNumber, textArea } = useForm({
        name: '',
        type: 1,
        weight: 0,
        description: '',
    })

  return (
    <Form>
        <Form.Item required label="Name" {...useFormItem('name')}>
            <Input {...input('name', {
                validator: form => !form.formState.name && { name: 'Name required!' },
            })} />
        </Form.Item>
        <Form.Item required label="Type" {...useFormItem('type')}>
            <Radio.Group {...radio('type', {
                onChange: e => +e.target.value,
            })}>
                <Radio value={1}>Type1</Radio>
                <Radio value={2}>Type2</Radio>
            </Radio.Group>
        </Form.Item>
        <Form.Item required label="Weight" {...useFormItem('weight')}>
            <InputNumber {...inputNumber('weight', {
                validator: form => {
                    const value = form.formState.weight

                    if (!value && value !== 0) {
                        return { weight: 'Weight required!' }
                    }

                    if (isNaN(+value)) {
                        return { weight: 'Weight must be a number' }
                    }
                },
            })} />
        </Form.Item>
        <Form.Item label="Description" {...useFormItem('description')}>
            <Input.TextArea {...textArea('description')} />
        </Form.Item>
    </Form>
  )
}

My API Proposal

useForm(initialState)

Create the form in the function components, it returns FormObject which including some sub hooks, they will be introduced later.

Params

  • initialState: { [key: string]: string | number | string[] | number[] } the initial state of the form.

Returns

  • FormObject: including form value, form item hooks and so on.

FormObject.form: formStateObject

All form states are stored in FormObject.form:

  • FormObject.form.formState form item and it’s value
  • FormObject.form.touchedObject form item touch state
  • FormObject.form.validityObject form item touch validity
  • FormObject.form.errorObject form errors

Example

// formStateObject
{
    formState: { name: 'Jason', age: 1004 },
    touchedObject: { name: false, age: true },
    validityObject: { name: false, age: false },
    errorObject: { age: 'Person age cannot greater than 100.' },
}

FormObject.useFormItem(formKey)

Proxy <Form.Item> props and auto set validate info or error status, like getFieldDecorator.

Params

  • formKey: string form key which had defined in initialState.

Returns

The same as props of <Form.Item>

  • validateStatus: 'success' | 'warning' | 'error' | 'validating'
  • help: string

FormObject.useValidator(validator[, deps])

Validate whole form state when form value changing.

Params

  • validator: function (formState, setters): void

    • formState: formStateObject
    • setters: { setValidityObject, setErrorObject }
  • deps: any when deps change, validator will be fired, default is formStateObject.formState

FormObject.input(formKey[, options])

FormObject.radio(formKey[, options])

FormObject.inputNumber(formKey[, options])

FormObject.textArea(formKey[, options])

FormObject.select(formKey[, options])

Hook Ant Design components

Params

  • formKey: string form key which had defined in initialState.
  • options
    • options.validator: function (value, setValidityObject): ErrorObject validate this form item
      • value: any value of formKey
      • setValidityObject: function () {}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Render Props vs React Hooks: Which Is More Efficient?
I started a twitter discussion with the same question, trying to understand if people have strong opinions about hooks and render props.
Read more >
Render Props - React
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render...
Read more >
Render Props vs React Hooks - Miroslav Nikolov
Hooks and render props can solve the same problem. It is conceptually about moving state away from your components, so that it is...
Read more >
Exploring Render Props Vs. React Hooks In 2020 - HackerNoon
Unloading the Form component state-wise using the render props approach requires you to create a wrapper component. So, no hooks on the ...
Read more >
React render props vs. custom Hooks - LogRocket Blog
Using a render prop can negate the advantage that comes from using PureComponent if we create a function assigned inside the render method....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found