2

I'm trying to add an event listener for clicks but it's saying that classList doesn't exist on type EventTarget.

class UIModal extends React.Component<Props> {
    handleClick = (e: Event) => {
        if ((e.target as EventTarget).classList.contains('modal-mask')) {
            this.props.close();
        }
    }

    componentDidMount() {
        window.addEventListener('click', this.handleClick);
    }

    componentWillUnmount() {
        window.removeEventListener('click', this.handleClick);
    }

    render() {
        return (
            <div className="modal-mask">
                <div className="modal">
                    {this.props.children}
                </div>
            </div>
        );
    }
}
1

2 Answers 2

2

Maybe you should try e.target as Element?

Sign up to request clarification or add additional context in comments.

Comments

0

e.target should be e.currentTarget

There's a bit of a discussion about this here https://github.com/Microsoft/TypeScript/issues/299

1 Comment

It should be target unless if he's doing event delegation (ie: attaching handler to a top level div, and wanting to work with the element that triggered it) (currentTarget will be the element that listener was attached to)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.