I'm new to react and have a small requirement to display the user input form data to json array in UI. Here is the form looks like:
input:
field1:12
field2:12
input:
field1:12
field2:12
outut:
field1:12
field2:12
outut:
field1:12
field2:12
I have already implemented add/remove functionality to clone input and output section in the form. My end goal is to display the input & output form data as below json format:
{
"input": [
{
field1:12,field2:12
},
{
field1:12,field2:12
}
],
"output": [
{
field1:12,field2:12
},
{
field1:12,field2:12
}
]
}
IN my form component class below code is being used to render :
render() {
var fieldsArray = [];
return (
<div>
<div id="input_section">
<table><tr><td><h3>Input</h3></td></tr>
<tr>
<td>
<li><label> field1 : </label><input type="text" size="100" name="id" onChange={this.onInputChange} /></li>
<li><label> field2 : </label><input type="text" size="100" name="inputType" onChange={this.onInputChange} /></li>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<button onClick={this.addElement}>+</button>
<button onClick={this.removeElement}>-</button>
</div>
<div id="output_section">
<table><tr><td><h3>Output</h3></td></tr>
<tr>
<td>
<li><label> field1 : </label><input type="text" size="100" name="id" onChange={this.onOutputChange} /></li>
<li><label> field2 : </label><input type="text" size="100" name="outputType" onChange={this.onOutputChange}/></li>
<br/>
</td>
</tr>
</table>
<button onClick={this.addElement}>+</button>
<button onClick={this.removeElement}>-</button>
</div>
<table>
<tr>
<td>
<button onClick={this.onSubmitForm}>Preview</button>
</td>
</tr></table>
</div>
);
to initialize the state i have below code:
this.state = {
input: {},
output:{}
};
In my parent component , i set the form data to state and finally using below code i render the same:
constructor(props) {
super(props);
this.state = {
input:{},
transform:{},
output:{}
};
this.submitForm = this.submitForm.bind(this);
}
submitForm(values) {
this.setState({ values })
}
render() {
const test = this.state.values;
let obj = Object.assign({}, test ); // creates a brand new object
//forming the json array in desired format
Object.keys(obj).forEach(key=>obj[key]=[obj[key]]);
return (
<div>
<FormDemo1
onFormSubmit={this.submitForm}/>
<div>
<JSONPretty id="json-pretty" data={obj}></JSONPretty>
</div>
</div>
);
}
}
Can anyone help me on iterating the each section input/output and store the same into my json array as per above json format.