Search code examples
javascriptformsreactjseventsonfocus

OnFocus and onBlur get fired 3 Times without focusing or leaving input Field


I made a new component for my input field in this component i tried to give the input field a class when it is focused and remove it when the focus get´s lost. Sidenote the form is in a Modal (npm react-responsive-modal). as soon as the modal and the input component gets loaded the onFocus and onBlur event get triggerd 3 Times each.

Here the form.js component

import React, { Component } from 'react';

class FormInput extends Component {

    constructor(props) {
        super(props);

        this.state = {
            selected: false,
        };
    }

    onFocus = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: true });
        console.log("Focus")
    };

    onBlur = () => { // -> Gets triggered 3 Times
        //this.setState({ selected: false });
        console.log("Leave")
    };

    render() {
        return (
            <div className="input" >
                <input onFocus={this.onFocus()} onBlur={this.onBlur()} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
                <label className="input-label" htmlFor={this.props.id}>E-Mail</label>
            </div>
        );
    }
}

export default FormInput;

The render function of the parent component.

render() {
    return (
        <Modal open={this.state.open} onClose={this.onCloseModal} little>
            <div className="App">
                {this.state.errors.map((error) => {
                    return <li key={error}>{error}</li>
                })}
                <form onSubmit={ this.onFormSubmit } autoComplete="off">
                    <FormInput placeholder="E-Mail" type="text" id="email"/>
                    <input type="submit" />
                </form>
                <button onClick={ this.logout }>Logout</button>
            </div>
        </Modal>
    );
}

Solution

  • When you are setting the onFocus and onBlur attribs, you are actually calling the function immediately. You need to remove the () after the function name:

     <input onFocus={this.onFocus} onBlur={this.onBlur} placeholder={this.props.placeholder} type={this.props.type} id={this.props.id} />
    

    You see the functions being called three times because each time the component renders, it is calling those functions.