Skip to content

Instantly share code, notes, and snippets.

@igrek8
Created February 21, 2018 11:08
Show Gist options
  • Save igrek8/155df21f2fc69114176a7ccd47732de1 to your computer and use it in GitHub Desktop.
Save igrek8/155df21f2fc69114176a7ccd47732de1 to your computer and use it in GitHub Desktop.
Recusive props in redux-form, Recursive render
/* eslint-disable react/prefer-stateless-function */
import React from 'react';
import { reduxForm, FieldArray, Field, FormSection } from 'redux-form';
import { TextField } from 'redux-form-material-ui';
const getDepth = (name) => {
if (name) {
const match = name.match(/children\[\d\]/g);
if (match) {
return match.length;
}
}
return 0;
};
const Children = ({ fields }) => fields.map((member, _, props) => (
<FormSection
key={member}
name={member}
component={Parent}
depth={getDepth(member)}
/>
));
class Parent extends React.PureComponent {
static defaultProps = {
depth: 0,
}
render() {
const content = (
<div
className="node"
style={{ marginLeft: 10 * this.props.depth }}
>
<Field
name="id"
component={props => `Member ${props.input.value}`}
/>
<Field
name="name"
component={TextField}
style={{ marginLeft: 15 }}
/>
<FieldArray
name="children"
component={Children}
/>
</div>
);
if (this.props.depth === 0) {
return (
<form onSubmit={this.props.handleSubmit}>
{content}
<button type="submit">Submit</button>
</form>
)
}
return content;
}
}
export default reduxForm({
form: 'rule',
initialValues: {
id: 1,
name: '',
children: [
{
id: 2,
name: '',
children: [
{
id: 3,
name: '',
children: [
{
id: 4,
children: []
},
],
},
],
},
],
},
})(Parent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment