So i am trying to create a dynamic form with a couple of HTML inputs. i have an array of object Forms which contain the type of input that should be rendered. Currently i am able to render a couple of inputs like text area but how do i deal with radios, check boxes, selects along with their options? Any help will be appreciated.
See this CodeSandbox.
Check this Sample Code:-
class App extends React.Component {
state = {
Forms: [{
name: "select",
type: "select",
options: ["a", "b", "c"]
},
{
name: "Radio",
type: "radio",
options: ["a", "b", "c"]
},
{
name: "Date",
type: "date",
value: "2018-07-22"
},
{
name: "Text Input",
type: "text",
value: "text input"
},
{
name: "Checkbox",
type: "checkbox",
options: ["a", "b", "c"]
},
{
name: "Textarea",
type: "textarea",
value: "text area"
}
]
};
renderForm = () => {
return this.state.Forms.map((form, index) => ( <
label key = {index} > { form.name}
<input type = { form.type }
value = { form.value } />
<select/ >
</label>
));
};
render() {
return <div > {
this.renderForm()
} < /div>;
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Thank you for all the help. :)
switch(form.type)inside your map and return the appropriate component for each case :)