Skip to content

Instantly share code, notes, and snippets.

@romelgomez
Created February 23, 2023 14:36
Show Gist options
  • Save romelgomez/857f3dd7677256241f61c34f057923b3 to your computer and use it in GitHub Desktop.
Save romelgomez/857f3dd7677256241f61c34f057923b3 to your computer and use it in GitHub Desktop.
ant form-methods-form
import { Form, Input, Button, Select, Card } from 'antd';
const { Option } = Select;
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
export const FormMethodsForm = () => {
const onFinish = (values: any) => {
console.log('Success:', JSON.stringify(values));
};
const [form] = Form.useForm();
const onGenderChange = (value: string) => {
// TODO: example on how to set the value of some imput
switch (value) {
case 'male':
form.setFieldsValue({ note: 'Hi, man!' });
return;
case 'female':
form.setFieldsValue({ note: 'Hi, lady!' });
return;
case 'other':
form.setFieldsValue({ note: 'Hi there!' });
}
};
// to reset the form
const onReset = () => {
form.resetFields();
};
// setting the form inputs with default values:
const onFill = () => {
form.setFieldsValue({
note: 'Hello world!',
gender: 'male',
});
};
return (
<Card title="Example form - 002">
<div>
<Form
// styles
// {...layout}
// [styles]
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
// [settings]
form={form}
name="control-hooks"
// [events]
onFinish={onFinish}
>
{/* simple input */}
<Form.Item name="note" label="Note" rules={[{ required: true }]}>
<Input />
</Form.Item>
{/* select input */}
<Form.Item name="gender" label="Gender" rules={[{ required: true }]}>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
{/* Input dinamico */}
<Form.Item
noStyle
// [validacion]
shouldUpdate={(prevValues, currentValues) =>
prevValues.gender !== currentValues.gender
}
>
{/* method for get some input value */}
{({ getFieldValue }) =>
getFieldValue('gender') === 'other' ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[{ required: true }]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
</div>
</Card>
);
};
export default FormMethodsForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment