Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  42] [ 1]  / answers: 1 / hits: 8643  / 4 Years ago, mon, october 12, 2020, 12:00:00

I have these states in my component.


     const [initialValues, setInitialValues] = useState({
name: "",
name2: "",
items: []
});

name and name2 combined together and made an array {name: 'sss', name2: 'sss'} and push to the items array. The pushing part is okay. The only problem is who to remove an item on that array.


This is my code https://codesandbox.io/s/material-demo-forked-u2qzv?file=/demo.js:260-362


Normal array methods seem not to work here.


How do I fix React and Formik?


More From » reactjs

 Answers
16

You could use Formik function setValues to set form values


{
values.items.map((e, i) => (
<div key={e.i}>
<Button
variant='contained'
onClick={() => {
setValues({
name: '',
name2: '',
items: values.items.filter((newE) => newE !== e), // Remove clicked item
})
}}
>
remove {e.name}
</Button>
</div>
))
}

The full code snippet is below:


/* eslint-disable no-use-before-define */
import React, { useState } from 'react'
import { Button } from '@material-ui/core'

import { Formik, Form, Field } from 'formik'
import { TextField } from 'formik-material-ui'
export default function ComboBox() {
const [initialValues, setInitialValues] = useState({
name: '',
name2: '',
items: [],
})

return (
<Formik
initialValues={initialValues}
onSubmit={() => {}}
enableReinitialize
>
{({
isValid,
dirty,
values,
handleChange,
handleBlur,
setFieldValue,
setValues,
}) => {
return (
<Form>
<div>
<Field
name='name'
label='Name'
variant='outlined'
component={TextField}
variant='outlined'
fullWidth
/>
<Field
name='name2'
label='Name2'
variant='outlined'
component={TextField}
variant='outlined'
fullWidth
/>
</div>

<Button
variant='contained'
onClick={() => {
console.log('values', values)
setFieldValue(`items[${values.items.length}]`, {
name: values.name,
name2: values.name2,
})
}}
>
add item
</Button>

{values.items.map((e, i) => (
<div key={e.i}>
<Button
variant='contained'
onClick={() => {
setValues({
name: '',
name2: '',
items: values.items.filter((newE) => newE !== e), // Remove clicked item
})
}}
>
remove {e.name}
</Button>
</div>
))}
</Form>
)
}}
</Formik>
)
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const agents = [
{ name: 'Pathum', id: 1 },
{ name: 'Chamod', id: 2 },
{ name: 'Avishka', id: 3 },
]

[#2506] Wednesday, October 7, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;