Skip to content

Instantly share code, notes, and snippets.

@apps-manager
Created August 13, 2018 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apps-manager/2036514f03cdfe4da3bcdbd06ac78353 to your computer and use it in GitHub Desktop.
Save apps-manager/2036514f03cdfe4da3bcdbd06ac78353 to your computer and use it in GitHub Desktop.
import React from 'react';
import PropTypes from 'prop-types';
import {Form} from 'pivotal-ui/react/forms';
const hasName = col => col && col.props && col.props.name;
const getFields = children => React.Children.toArray(children).filter(Boolean).reduce((memo, {props: {children}}) => ({
...memo,
...React.Children.toArray(children).filter(hasName).reduce((memo, {props}) => ({...memo, [props.name]: props}), {})
}), {});
export class GridForm extends React.Component {
static propTypes = {
onModified: PropTypes.func,
onSubmit: PropTypes.func,
onSubmitError: PropTypes.func,
afterSubmit: PropTypes.func,
resetOnSubmit: PropTypes.bool
};
constructor(props) {
super(props);
this.state = {fields: getFields(props.children)};
}
shouldComponentUpdate({children}, nextState) {
nextState.fields = getFields(children);
return true;
}
render() {
const {children, ...others} = this.props;
return (
<Form {...{fields: this.state.fields, ...others, ref: form => this.form = form}}>
{({fields, ...form}) => React.Children.toArray(children).filter(Boolean)
.map((row, key) => React.cloneElement(row, {
...form, key, children: React.Children.toArray(row.props.children).filter(Boolean)
.map((col, key) => React.cloneElement(col, {
...form, key, colProps: col.props,
children: col.props.name ? fields[col.props.name] : col.props.children
}))
}))}
</Form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment