Home > Software design >  Why is event object not accessable once I wrap two functions in anonymous function in submit handler
Why is event object not accessable once I wrap two functions in anonymous function in submit handler

Time:04-14

So I have wrapped two functions in a onClick handler like so:

const PlannerDetailsFooter = (props) => {

    const [checked, setChecked] = useState(false);

    const handleChange = () => {
        setChecked((prev) => !prev);
    };

    return (
        <div className="details-footer w-full p-4 bottom-0 absolute border-t-1">
            {props.emailConfig.isHidden ? null :
                        <button id="mail-button"
                    
                    onClick={() => {props.emailHandler(); handleChange()}}
            >{props.emailConfig.buttonText}</button>
        </div>
    )
}

This is one of the two called functions which is located in the parent component

    const emailHandler = (event) => {
        if (event.target.id === "mail-button") {
            setEmailConfig({...emailConfig, isHidden: false, buttonText: 'Send Now'})
        } else {
            setEmailConfig(event.target.value)
        }
    }

Now I get the error

Cannot read properties of undefined (reading 'target')

Using this solution the handler in the parent component can access the event object:

onClick={props.emailHandler}

CodePudding user response:

When you use onClick={props.emailHandler} you are binding emailHandler to onclick and it will receive the parameters passed by onclick.

Now, when you use () => {props.emailHandler(); ...} You are not passing the parameters to emailHandler. To fix this you can do (e) => {props.emailHandler(e); ...}

  • Related