I am using Formik to create a form which has a Dropdown and submit button. Upon clicking any item from dropdown, I render a toggle option. The problem I am facing is that if I have two toggles, and first one is OFF, and second one is ON. And now if I delete first one, value of second one also changes to that of first one. How do I fix it. Any help is appreciated. Here is the link to my code-
https://codesandbox.io/s/kw3w0xlqjv
The problem was that of key attribute. Correct solution-
import React from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import { Dropdown, DropdownItem } from "carbon-components-react";
import { Formik, Field, Form, FieldArray } from "formik";
const initialValues = {
attributes: []
};
const App = () => (
<div>
<Formik
initialValues={initialValues}
onSubmit={values => console.log(values)}
render={({ values }) => {
return (
<Form>
<FieldArray
name="attributes"
render={({ remove, push }) => (
<div>
{values.attributes.length > 0 &&
values.attributes.map((eachAttribute, index) => (
<div className="row" key={eachAttribute.attributeName}>
<div className="col">
<label>{eachAttribute.attributeName}</label>
<Field
name={`attributes.${index}.values.in.${0}`}
type="checkbox"
id={`boolenField.${index}`}
className="bx--toggle"
/>
<label
className="bx--toggle__label"
for={`boolenField.${index}`}
>
<span className="bx--toggle__text--left">Off</span>
<span className="bx--toggle__appearance" />
<span className="bx--toggle__text--right">On</span>
</label>
{/*<Field
name={`attributes.${index}.values.in.${0}`}
placeholder="attribute value"
type="text"
/>*/}
</div>
<div className="col">
<button
type="button"
className="secondary"
onClick={() => remove(index)}
>
X
</button>
</div>
</div>
))}
<Dropdown
className="some-class"
ariaLabel="dropdown menu label"
onChange={e =>
push({ attributeName: e.value, values: { in: [] } })
}
defaultText="Pick attribute"
>
<DropdownItem itemText="Option 1" value="option1" />
<DropdownItem itemText="Option 2" value="option2" />
<DropdownItem itemText="Option 3" value="option3" />
<DropdownItem itemText="Option 4" value="option4" />
<DropdownItem itemText="Option 5" value="option5" />
</Dropdown>
{/*<button
type="button"
className="secondary"
onClick={() =>
push({ attributeName: "", values: { in: [] } })
}
>
Add attribute
</button>*/}
</div>
)}
/>
<button type="submit">Submit</button>
</Form>
);
}}
/>
</div>
);
render(<App />, document.getElementById("root"));
Thank you Ricardo Brambila.
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.