rajiv dahal
rajiv dahal

Reputation: 69

All value fields are changing to the same value if I change one input in react

This is my code:

{
    lining.hitprescription ?
    <div className="prescription-form">
        {
            medicine.map((item, index) => {
                return <>
                    <div className="form-items" key={index}>
                        <label htmlFor="name">Medicine {index + 1}:</label>
                        <input className="prescription-input"{...formik.getFieldProps("medicine")}></input>
                    </div>
                </>
             })
         }
         <div className="form-items" onClick={addMoreMedicine}>
             <label htmlFor="addmore" style={{ color: "blue" }}>Add More <Add></Add></label>
         </div>
    </div>: null
}

inside react JSX, I am mapping the input form fields where medicine is initialized as

const [medicine, setmedicine] = useState(["", ""])

and I am using formik where values are initialized as

const formik = useFormik({
    initialValues: {
        basicInfo: '',
        labTestId: [],
        appointmentId: null,
        medicine: ""
    },
    validate: values => {
        let errors = {}
        if (!values.basicInfo) {
            errors.basicInfo = "Required!"
        }
        return errors
    }
})

the problem I get is if I change one input field then the same value is shown in other input fields during the time of changing field , how to solve this problem?

Upvotes: 0

Views: 1368

Answers (1)

Vitaliy Rayets
Vitaliy Rayets

Reputation: 2404

This behavior because you set state medicine with type array to each input. When you map array of medicine you must set state by index for each input . Example:

{...formik.getFieldProps("medicine")[index]}

codesandbox

Upvotes: 1

Related Questions