Skip to content

Instantly share code, notes, and snippets.

@CaptainChemist
Created January 8, 2020 22:50
Show Gist options
  • Save CaptainChemist/16647d001ccff63998e8cd8cd00eb106 to your computer and use it in GitHub Desktop.
Save CaptainChemist/16647d001ccff63998e8cd8cd00eb106 to your computer and use it in GitHub Desktop.
// components/CreateRecipe.tsx
import { Form, Row, Col, Button } from 'antd';
import { submitForm } from '../utils/submitForm';
import { GenerateInput } from './GenerateFields';
export const CreateRecipe = () => {
const initiateCreateRecipe = () => {
console.log('submitted Form');
};
const { inputs, handleInputChange, handleSubmit } = submitForm(
{
title: '',
},
initiateCreateRecipe,
);
return (
<Form onSubmit={handleSubmit}>
<GenerateInput
name="title"
value={inputs.title}
handleInputChange={handleInputChange}
/>
<Row>
<Col span={16} />
<Col span={4}>
<Form.Item label="Create Recipe">
<Button type="primary" htmlType="submit">
Create Recipe
</Button>
</Form.Item>
</Col>
</Row>
</Form>
);
};
// components/GenerateFields.tsx
import { Row, Col, Form, Input } from 'antd';
type InputType = {
name: string;
value: string;
handleInputChange?: (event: any) => void;
};
export const GenerateInput = ({
name,
value,
handleInputChange,
}: InputType) => (
<Row>
<Col span={12} offset={6}>
<Form.Item label={`${name}`}>
<Input
placeholder={`${name}`}
name={`${name}`}
value={value}
onChange={handleInputChange}
/>
</Form.Item>
</Col>
</Row>
);
// utils/submitForm.tsx
import { useState } from 'react';
import * as _ from 'lodash';
export const submitForm = (initialValues, callback) => {
const [inputs, setInputs] = useState(initialValues);
const handleSubmit = event => {
if (event) event.preventDefault();
callback();
setInputs(() => ({ ...initialValues }));
};
const handleInputChange = event => {
event.persist();
setInputs(inputs => {
const newInputs = _.cloneDeep(inputs);
_.set(newInputs, event.target.name, event.target.value);
return newInputs;
});
};
return {
inputs,
handleInputChange,
handleSubmit,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment