Created
August 13, 2018 21:38
-
-
Save apps-manager/2036514f03cdfe4da3bcdbd06ac78353 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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