Skip to content

Instantly share code, notes, and snippets.

@tapandave08
Created November 30, 2017 12:58
Show Gist options
  • Save tapandave08/64f7debe6755cb45c7882ee573b55440 to your computer and use it in GitHub Desktop.
Save tapandave08/64f7debe6755cb45c7882ee573b55440 to your computer and use it in GitHub Desktop.
dynamic form
const renderField = ({ input, field }) => {
const { type, placeholder, name, value, ...props } = field;
const validate = applyRules(field.checkRules);
const divStyle = {
display: "block"
};
if (type === "text" || type === "email" || type === "number") {
return (
<Input
{...input}
name={name}
type={type}
label={placeholder || name}
validate={validate}
{...props}
/>
);
} else if (type === "checkbox") {
return (
<Input
{...input}
name={name}
type={type}
label={placeholder || name}
defaultChecked={field.value}
validate={validate}
{...props}
/>
);
} else if (type === "select") {
const { options } = field;
return (
<select name={field.name} onChange={input.onChange} style={divStyle}>
{options.map((option, index) => {
return (
<option
key={index}
value={option.defaultValue || option.value}
selected={option.defaultValue}
>
{option.label}
</option>
);
})}
</select>
);
} else {
return <div>Type not supported.</div>;
}
};
class SimpleForm extends Component {
constructor(props) {
super(props);
}
submit(values) {
this.props.submitformvalue(values);
}
render() {
const {
handleSubmit,
fields,
initialValues,
pristine,
submitting,
valid
} = this.props;
return (
<form onSubmit={handleSubmit(this.submit.bind(this))}>
{fields.map(field => (
<div key={field.name}>
<Field name={field.name} component={renderField} field={field} />
</div>
))}
<Button
waves="light"
type="submit"
disabled={pristine || submitting || !valid}
>
Update
</Button>
</form>
);
}
}
function mapStateToProps(state, props) {
return {
initialValues: intialvaluesfields(props)
};
}
function intialvaluesfields(props) {
var obj = props.fields.reduce(function(acc, cur, i) {
var valueoptions;
if (cur.value || cur.options) {
if (cur.options) {
var optionsvalue = cur.options.find((i, index) => {
if ("defaultValue" in i) {
return true;
}
});
valueoptions =
optionsvalue === undefined
? cur.options[0].value
: optionsvalue.defaultValue;
}
acc[cur.name] = cur.value || valueoptions;
}
return acc;
}, {});
return obj;
}
const formgenerate = reduxForm({
form: "simple",
enableReinitialize: true
})(SimpleForm);
export default connect(mapStateToProps)(formgenerate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment