Search code examples
javascriptreactjsvalidationonblurreactstrap

Why is this handleBlur function with event parameters when the event parameter is not used inside the function?


Could you help me understand why this function below has the event parameter when it is not being used inside the function?

handleBlur = field => event => {
 this.setState({
     touched: { ...this.state.touched, [field]: true }
 })
}

Why this function below not working when I tried?

handleBlur(field) {
    this.setState({
        touched: { ...this.state.touched, [field]: true }
    })
}

This function is being used as per below:

<FormGroup row>
                                <Label htmlFor='firstname' md={2}>First Name</Label>
                                <Col md={10}>
                                    <Input type='text' id='firstname' name='firstname'
                                        placeholder='First Name'
                                        value={this.state.firstname}
                                        valid={errorMessages.firstname === ''}
                                        invalid={errorMessages.firstname !== ''}
                                        onChange={this.handleInputChange}
                                        onBlur={this.handleBlur('firstname')}
                                    />
                                    <FormFeedback>{errorMessages.firstname}</FormFeedback>
                                </Col>
                            </FormGroup>

Solution

  • handleBlur = field => event => {
     this.setState({
         touched: { ...this.state.touched, [field]: true }
     })
    }
    

    This is a double arrow function, in this case the function handleBlur passes the value field and returns a function with event as an input, almost like this:

        function handleBlur(field) {
         return function(event) {
            //do something
         }
        }
    

    You can find a very good explanation here, using your own example:

    What do multiple arrow functions mean in javascript?

    I don't know why that code is not using the event, but it's there.