lundi 23 décembre 2019

ReactJS -> problem with 'clearing' input forms

I've got simple form. Every time I try to fill a form, the rest of the fields clears. In addition validation errors are displayed below each field instead of just one. How to fix this? This how it looks before any action: https://i.imgur.com/zjGsNRL.png And this how it looks after wrong data: https://i.imgur.com/pSh6rFM.png

My constructor:

constructor(props) {
        super(props);
        this.state = {
            title: {
                text: ''
            },
            foods: [{
                text: '',
                kcal: '',
                protein: '',
                carbohydrate: '',
                fat: ''
            }],
        };

Handlers and validation f():

 handleKcalChange(event, index) {
        const foods = this.state.foods.slice();
        const value = event.target.value;


        foods[index] = {
            kcal: value,
            ...this.validateParam(value)
        }

        this.setState({
            foods: foods
        });
    }
 handleProteinChange(event, index) {
        const foods = this.state.foods.slice();
        const value = event.target.value;

        foods[index] = {
            protein: value,
            ...this.validateParam(value)
        }

        this.setState({
            foods: foods
        });
    }
validateParam = (paramNumber) => {
        if(paramNumber < 0) {
            return {
                validateStatus: 'error',
                errorMsg: 'Number can`t be smaller than 0.'
            }
        } else if(paramNumber > 1000) {
            return {
                validateStatus: 'error',
                errorMsg: 'Number is too big!'
            }
        } else {
            return {
                validateStatus: 'success',
                errorMsg: null
            }
        }
    }



Aucun commentaire:

Enregistrer un commentaire