How to dynamically create a form that adds dynamic fields and nested array using the formik fieldArray - reactjs

I am trying to create dynamic form with fieldArray in react. My code looks like this
<Formik initialValues={{
data:[],
}}
onSubmit={(values)=>{
console.log(values)
}}
>
{
(formik)=>(
<Form>
<h2>form starts here</h2>
<FieldArray name='data' render={
(arrayHelpers)=>{
return(
<div>
<button type='button' onClick={()=>arrayHelpers.insert(formik.values.data.length + 1,{question:'',quesType:'',answers:['']})}>Add</button>
{/* starts */}
{formik.values.data.map((d,index)=>(
<div key={index}>
<label htmlFor={`data.${index}.question`}>question</label>
<Field name={`data.${index}.question`} type='text' id={`data.${index}.question`}/>
<label htmlFor={`data.${index}.quesType`}>quesType</label>
<Field as="select" name={`data.${index}.quesType`}>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</Field>
</div>
// end
))}
</div>
);
}
}/>
<button type='submit'>submit</button>
</Form>
)
}
</Formik>
so after clicking add button my initialValue looksLike
data[{question:'',questype:'',answers:[]}]
Now after the select option I want to add a button that will add values in the answers array. I tried looping the d.answers but the answers property was not accessible even though I have the property. So, How to achieve this? Thanks in advance!

Related

how to pass array values to Formik select

I am using Formik for a bunch of admin console forms that I have in my application. So far I did not have this use case.
My Formik forms use one of 2 custom components, either a Myinputtext(input box) or a MySelect(drop down). I dont have a need for any other components so far. Here is how my Myselect component looks like.
const MySelect = ({ label, ...props }) => {
const [field, meta] = useField(props);
return (
<div>
<label htmlFor={props.id || props.name}>{label}</label>
<select className={props.className} {...field} {...props} />
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</div>
);
};
Over in the form I am passing values to this component like this
<MySelect className="select-input" label="Losing Player" name="losingPlayer">
<option value="">Select Losing Player</option>
<option value="player1">{state.Player1Name} </option>
<option value="player2">{state.Player2Name} </option>
All of this works for a few forms I have built so far. In the fourth form now, data coming back from the back end is coming as an array and I am trying to pass the array as input to the myselect component
<MySelect className="select-input" label="Losing Player" name="losingPlayer">
<option value="">Select Losing Player</option>
<option value="player1">{name of array object} </option>
This is failing and not providing the right result.
In the formik official docs it says there is a way to handle array objects like this
<Form>
<Field name="friends[0]" />
<Field name="friends[1]" />
<button type="submit">Submit</button>
</Form>
</Formik>
But my array size can be dynamic and I cannot hardcode, 0,1 like above.
I tried rendering the array inside the select component like this,
<MySelect className="select-input" label="Winning Player" name="winningPlayer">
{props.initialValues.map((player) => {
<option key={player} value={player}> {player} </option> })} </MySelect>
this does not throw any errors. but the drop down is displayed empty.
I am basically hoping to have the names in the array displayed as the dropdown. What is the right solution to tackle this?
This finally worked:-
return (
<div>
<label htmlFor={props.id || props.name}>{label}</label>
{!props.player ? <select className={props.className} {...field} {...props} />
:
<select className={props.className}>
{props.player.map((player) => {
return (
<option key={player} value={player}>
{player}
</option>
)
})}
</select>
}
{meta.touched && meta.error ? (
<div className="error">{meta.error}</div>
) : null}
</div>
You need to map your array and render options inside your select like this:
{options?.map(({ value }) => (
<option key={value} value={value}>
{value}
</option>
))}

Specify initial value for radio button

I want to the "Exact" radio button to be checked when a form is opened:
<Form
onSubmit={onSubmit}
initialValues={{ match_type: "exact" }}
render={({ handleSubmit, form, reset, submitting, pristine, values }) => (
<form
onSubmit={() => {
handleSubmit();
}}
>
<fieldset>
<legend>Match type</legend>
<Field name="match_type">
{({ input }) => (
<label>
<input {...input} type="radio" value="fuzzy" /> Fuzzy
</label>
)}
</Field>
<Field name="match_type">
{({ input }) => (
<label>
<input {...input} type="radio" value="exact" /> Exact
</label>
)}
</Field>
</fieldset>
<button type="submit">Save match</button>
</form>
)}
/>
The radio button remains unchecked. Any idea how I should get this to work? Note using <Field component="input" type="radio" .../> is not an option for me.
Codesandbox: https://codesandbox.io/s/react-final-form-reset-after-submit-forked-q6jyv?file=/index.js:359-1235
You can set the default to be checked in the tag.
<input {...input} type="radio" value="exact" checked />
I just needed to use the Field component properly:
<Field name="match_type" type="radio" value="fuzzy">
{({ input }) => (
<label>
<input {...input} /> Fuzzy
</label>
)}
</Field>
This way the <input will get what it needs spread in from the argument to the render prop.
If you inspect your component in codesandbox provided, you can see that Field component doesn't have value prop. I'm attaching a screenshot here
You have a few options to solve this. The main idea though is to understand what you are passing when you say {...input} In your Field component, you currently only have name prop, so you can add something like this
input={{ name: 'match_type', value: 'exact', onChange: (e) => (whatever you need on change) }}
RFF could be tricky with just setting value like that since source of truth lives in the form. So, you can also use a mutator functionality of the form. This is a good description of how to do it

Reactjs antd defaultValue return undefined

im trying to make an edit function, the problem come when im trying to get the value from the form, say a user is editing his name, but he does not edit his address, this will make address is undefined even though i already set a defaultValue inside it, this works before in my non antd form, here is my code
form :
<Form onFinish={this.edit}>
<Typography>Email</Typography>
<Form.Item
name="email"
>
<Input defaultValue={user.Email} value={user.Email} className="email form-control col-sm-6"/>
</Form.Item>
<Typography>Full Name</Typography>
<Form.Item
name="name"
>
<Input defaultValue={user.FullName} value={user.FullName} className="email form-control col-sm-6"/>
</Form.Item>
<Typography>Admin</Typography>
<Form.Item
name="admin"
>
{
(user.IsAdministrator)
? <div>
<Select value="yes">Admin
<Select.Option value="no">Not Admin</Select.Option>
</Select>
</div>
: <div>
<Select value="no">Not admin
<Select.Option value="yes">Admin</Select.Option>
</Select>
</div>
}
</Form.Item>
<Typography>Active Status</Typography>
<Form.Item
name="aktif"
>
{
(user.IsActive)
? <Toggle className="switch-lg" checked/>
: <Toggle className="switch-lg"/>
}
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login col-md-10">Submit</Button>
and here is how i get the value :
edit(values){
const name = values.name
const aktif = values.aktif
const index = this.state.id
console.log(values)
}
thanks before, anyhelp will be appreciated
As mentioned in the docs,
You cannot set value for each form control via value or defaultValue prop, you should set default value with initialValues of Form.
Example below:
<Form
onFinish={onFinish}
initialValues={{
residence: ['zhejiang', 'hangzhou', 'xihu'],
prefix: '86',
}}
>

How to get selected value in dropdown using Formik Field in React JS?

export class SelectFruitModal extends Component {
FruitList = ['Apple', 'Mango', 'Chickoo', 'others'];
FruitListItems = this.FruitList.map((fruit) => <option key={fruit}>{fruit}</option>);
handleChange(event){
alert('Event',event.target.value)
}
render() {
return (
<div>
<Modal>
<ModalBody>
<Formik
initialValues={{
FruitList: ''
}}
render={({}) =>
!isSubmitting ? (
<div>
<Row>
<Form>
<Row>
<Col>
<div className="form-group">
<Field
name="FruitList"
component="select"
className={
'form-control' +
(errors.FruitList &&
touched.FruitList
? ' is-invalid'
: '')
}
onChange={this.handleChange}
>
<option disabled="disabled" value="">
Select fruit
</option>
{this.FruitListItems}
</Field>
</div>
</Col>
</Row>
</Form>
</Row>
</div>
) : (
<PageSpinner />
)}
/>
</ModalBody>
</Modal>
</div>
);
}
}
export default SelectFruitModal;
1.In above code I have dropdown of FruitList
2.My requirement is when I select others value from the fruitlistItems then I should get one textArea beside it.
3.For that I need to get selected value from dropdown as 'others' so that i can enable field textbox.
4.How can I get selected value of dropdown ? I tried using onChange() and calling event value in it gives me empty value. Please help?

React Hooks Form Reset dont set Select to initial value

When clicking Reset, form should go back to initial values, but the Select element goes back to first option available, have used the same method for all other form elements, and they update correctly.
Have made a Codesandbox example of the problem : https://codesandbox.io/s/lively-snowflake-tf5te
function App() {
// Data for select dropdown box - selected is Lime
const SelectData = ["Grapefruit", "Lime", "Coconut", "Mango"];
// Selected Value
const selectedValue = "Lime";
// Set state
const [selectBox, setSelectBox] = useState(selectedValue);
// Submit finction
const handleSubmit = e => {
e.preventDefault();
alert(`Select Selection #1: ${selectBox}`);
};
// Reset function
const handleReset = () => {
setSelectBox(selectedValue);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>
When 'Reset' is clicked first options is selected
<br />
and not the state value.
</h2>
<form onSubmit={handleSubmit}>
<Select
label="Select Fruit"
value={selectBox}
handleChange={e => setSelectBox(e.target.value)}
data={SelectData}
/>
<br />
<br />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" onClick={handleReset} />
</form>
<br />
Selectbox state value: {selectBox}
<br />
</div>
);
}
Expected result, after Resetting Form, is that then Select element value is "Lime", but it is "Grapefruit".
I changed the value to defaultValue in your DropDown.js file and it worked like charm. Check the sandbox
<select defaultValue={value} onChange={handleChange}>
{data.map(item => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
Your code is correct. Your "bug" is due to the <input type='reset'/>.
Change it to a regular button and you'll see that it works just fine.
<button onClick={handleReset}>Reset</button>
https://codesandbox.io/s/dark-cdn-qchu5
From MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/reset
elements of type "reset" are rendered as buttons, with a default click event handler that resets all of the inputs in the form to their initial values.
This is concurring with your controlled component.
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>
When 'Reset' is clicked first options is selected
<br />
and not the state value.
</h2>
<form onSubmit={handleSubmit}>
<Select
label="Select Fruit"
value={selectBox}
handleChange={e => setSelectBox(e.target.value)}
data={SelectData}
/>
<br />
<br />
<input type="submit" value="Submit" />
{/* <input type="reset" value="Reset" onClick={handleReset} /> */}
<button onClick={handleReset}>Reset</button>
</form>
<br />
Selectbox state value: {selectBox}
<br />
</div>
);
Even though select is a controlled component, Form doesn't support onReset event. Thus, the behavior is similar to $form.reset() which will reset the select value to default value when button of type=Reset is clicked.
So an alternative is to use defaultValue prop in select or use a normal button with onChange prop.

Resources