Disclaimer: I'm new to ReactJS, Javascript and more generally to front-end development.
Hi everyone,
I decided to build a generic component to handle all the forms I'll be using in my project based on a given template.
Generation is quite simple: I loop on my template in Json and create the components I need.
But now I'm struggling to find a solution to retrieve the input values of those components without passing by some code generation writing the JS code.
p.s.: I'm using Material UI components.
Here is an example of template :
{ label: "General information",
elements: [ { label: "Firstname",
element: "textfield",
element_info: []
},
{ label: "Lastname",
element: "textfield",
element_info: []
},
{ label: "Email",
element: "textfield",
element_info: []
},
{ label: "Password",
element: "textfield",
element_info: []
},
{ label: "Phone number",
element: "textfield",
element_info: []
}
]
},
And here is my code so far :
render: function() {
var formPattern = this.props.form;
var form = [];
for (var paper in formPattern) {
var elements = formPattern[paper].elements;
var paper = [];
for (var element in elements) {
var label = elements[element].label;
if (elements[element].element == "selectfield") {
var element_info = elements[element].element_info;
var items = [];
for (var i = 0; i < element_info.length; i++) {
items.push(<MenuItem value={i+1} primaryText={element_info[i]} />);
}
paper.push( <SelectField>
{items}
</SelectField>);
} else if (elements[element].element == "toggle") {
paper.push(<Toggle label={label} />);
} else if (elements[element].element == "checkbox") {
paper.push( <Checkbox
label={label}
style={checkboxStyle}
/>);
} else {
paper.push(<TextField hintText={label} />);
}
}
form.push(<Paper style={paperStyle}>
{paper}
</Paper>);
}
return (
<div>
{form}
<FlatButton
label="Create"
onTouchTap={this.props.onNewClick}
/>
</div>
);
So if we just concentrate on the TextField component I would need to add a "onChange" property-like to get the input knowing that I don't know who's this field because I'm on a generic component.
Obvioulsy I need to be able to access to the result data from the parent component where I'll be playing with it.
I was thinking of concatenating all the values in a single string with a format like "fieldName:value," or even directly in a JSON format.
But: How do I retrieve those values?????? That's the question!
Here I am. I've been searching a solution for hours and you guys are my last chance /o/
Thank you in advance for your help!