DEV Community

zhangfisher
zhangfisher

Posted on

In React, quickly collect form data into a complex JSON object

-What would you do if you had a need for users to edit JSON data?
-What would you do if the structure of a JSON object is very complex?

For example, the following JSON object:

{
     "name": "John Doe",
     "age": 30,
     "skills": ["JavaScript", "Python", "HTML"],
     "vip":true,
     "level":1,
     "address": {
     "street": "TongYan",
     "city": "QuanZhou",
     books:[
         { name:"AutoStore",price:100,count:12 },
         { name:"AutoStore for React",price:200,count:1 }
     ]
}
Enter fullscreen mode Exit fullscreen mode

The actual JSON may be more complex. We recommend a simple way to use AutoStore, as follows:

import { useForm } from "@autostorejs/react"
export default ()=>{
const { Form,reset } = useForm({
     "name": "John Doe",
     "age": 30, 
     "skills": ["JavaScript", "Python", "HTML"],
     "vip":true,
     "level":1,
     "address": {
     "street": "TongYan",
     "city": "QuanZhou"
},
books:[
     { name:"AutoStore",price:100,count:12 },
     { name:"AutoStore for React",price:200,count:1 }
]
})
return (<Form>
    <input data-field-name="name"/>
    <input data-field-name="skills"/>
    <input data-field-name="age" type="number/>
    <input data-field-name="level" type="number/>
    <input data-field-name="vip" type="checkbox/>
    <input data-field-name="address.city" type="checkbox"/>
    <input data-field-name="address.street" type="checkbox"/>
   {
   books.map((book,index)=>{
      return (<>
        <input data-field-name={`books.${index}.name`} />
        <input data-field-name={`books.${index}.price`} />
        <input data-field-name={`books.${index}.count`} />
       </>)
   })
   }
  </Form>)
}

Enter fullscreen mode Exit fullscreen mode

Okay, now there is a bidirectional binding relationship between the form and the JSON object, and the data will be synchronized to JSON.

AutoStoreIt is an excellent front-end React state library that can easily achieve bidirectional binding between any complex JSON data object and form control.

Top comments (0)