In React, quickly collect form data into a complex JSON object
zhangfisher
Posted on November 21, 2024
-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 }
]
}
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>)
}
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.
💖 💪 🙅 🚩
zhangfisher
Posted on November 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
undefined I absolutely love when CSS gets new features (Even though it usually takes me years to remember to use them 😄)
November 27, 2024