DEV Community

zhangfisher
zhangfisher

Posted on

1

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay