Confirm one field based on another field in reduction form

I use redux-form , and my component has several FieldArray . One of the components of FieldArray creates a table, as shown in the screenshot. Here, each row is a Field component, including a check box. What I want to achieve is if the checkbox component on this line is checked, then only the price field is required.

I tried to solve this problem using validate.js as described in docs , but since this component has a structure like:

 <FirstComponent> <FieldArray component={SecondComponent} name="options" fruits={fruitsList} /> </FirstComponent> 

In my SecondComponent I repeat over fruitsList , and if the length is greater than 1, then I draw a ThirdComponent . This component is responsible for creating fruit lists, as shown in the screenshot. Having a certain degree of nesting, when I check the values, it has a lot of performance lag, my screen freezes until it displays ThirdComponent . Each component has a Fields bit, so it cannot easily merge them. Any simple way to solve this in an elegant way would be helpful. The logic for checking is as follows:

 props.fruitsList.map((fruit, index) => { const isChecked = values.getIn(['fruit', index, 'checked']) if (isChecked) { const price = values.getIn(['fruit', index, 'price']) if (price === undefined || price.length === 0) { errors.fruits[index] = { price: l('FORM->REQUIRED_FIELD') } } } return errors }) 

Form Sceenshot]

+5
source share
1 answer

For the synchronous validation function, all values ​​in the form are given. Therefore, if your checkbox is a form value, you have all the necessary information.

 function validate(values) { const errors = {} errors.fruits = values.fruits.map(fruit => { const fruitErrors = {} if (fruit.checked) { // only do fruit validation if it checked if (!fruit.price) { fruitErrors.price = 'Required' // Bad user!! } } return fruitErrors }) return errors } ... MyGroceryForm = reduxForm({ form: 'groceries', validate })(MyGroceryForm) 
+3
source

Source: https://habr.com/ru/post/1263966/


All Articles