简体   繁体   中英

Add input field on click react js from form object

I have the following snippet from my react app to generate the input fields for my form:

 const [profiles, setProfiles] = useState({ controls: [ { network: { elementType: "input", elementConfig: { type: "text", label: "Network", }, value: "Twitter", }, }, { username: { elementType: "input", elementConfig: { type: "text", label: "Username", }, value: "@john", }, }, { url: { elementType: "input", elementConfig: { type: "url", label: "URL", }, value: "https://example.co", }, }, ], });

Code snippet to generate Input field:

 const profilesControls = (controls) => { const formElementsArray = controls.map((item,index) =>({ id: Object.keys(item)[0], index:index, config: item[Object.keys(item)[0]], })) return formElementsArray; } let profileField = profilesControls.map((formElement) => ( <Input label={formElement.config.elementConfig.label} key={formElement.index} type={formElement.config.elementType} elementConfig={formElement.config.elementConfig} value={formElement.config.value} changed={(event) => arrayInputHandler(event, formElement.index, formElement.id) } /> ));

And a button and function attached to the button to add another set of [network, username, url]

 const handelAddField = () => { const fields = [...profiles.controls]; fields.map((item, i) => { setProfiles({...profiles, controls: [...profiles.controls, item]}) }); console.log(profiles.controls); };

With the handelAddField I can see the object pushed into the controls array of the state but the input fields are not generated in the form.

Update

Now only one input field is generated that is URL

you should all setProfiles for updating a state.

instead of profiles.controls.push(item) use:

setProfiles({...profiles, controls: [...profiles.controls, item]})

Found my own solution:

 const handelAddField = () => { const fields = [...profiles.controls]; fields.map((item, i) => { fields.push(item); }); setProfiles((prev) => ({...prev, controls:fields })); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM