ivantxo
ivantxo

Reputation: 639

How to capture click outside React component

I started to learn React and I am trying to implement a modal window. I am at the same time using TypeScript.

I wanted to capture a click outside my React component, so when I click outside the modal window, this one closes. I based my approach on this: How to capture click outside React component

import styled from 'styled-components';

const StyledModal = styled.div`
  width: 100%;
  background-color: #fff;
  box-shadow: 0 0 0.625rem, rgba(0, 0, 0, 0.2);

  @media (min-width: 576px) {
    width: 32rem;
  },
`;

class Modal extends React.Component<ModalProps> {
    private modal: HTMLDivElement;

    onOutsideClick = (e: any) => {
      if (!_.isNil(this.modal)) {
        if (!this.modal.contains(e.target)) {
          this.onClose(e);
        }
      }
    }

    componentDidMount() {
      document.addEventListener('mousedown', this.onOutsideClick, false);
    }

    componentWillMount() {
      document.removeEventListener('mousedown', this.onOutsideClick, false);
    }

    render() {
        <div>
            <StyledModal ref={(node: any) => { this.modal = node; }}>
            ...
            </StyledModal>
        </div>
    }
}

The issue is whenever I click inside or outside the modal I get this error, which I don't know what it is or how to fix it:

enter image description here

Any lights please let me know...

Upvotes: 3

Views: 2687

Answers (3)

Tushar Sharma
Tushar Sharma

Reputation: 302

If you want to use a tiny component (466 Byte gzipped) that already exists for this functionality then you can check out this library react-outclick. It lets you capture clicks outside of a component.

The good thing about the library is that it also lets you detect clicks outside of a component and inside of another. It also supports detecting other types of events.

Upvotes: 0

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4391

From styled-components v4 onward it is ref prop.

constructor(props) {
  super(props);
  this.inputRef = React.createRef();
}

render() {
  return (
   <Input
      ref={this.inputRef}
    />
  );
}

For more info Refs

Upvotes: 0

Kenneth Truong
Kenneth Truong

Reputation: 4166

Since your StyledModal is styled-components you need to add innerRef to be able to get the DOM node. Keep in mind innerRef is a custom prop only for styled-components

https://github.com/styled-components/styled-components/blob/master/docs/tips-and-tricks.md#refs-to-dom-nodes

<StyledModal innerRef={(node: any) => { this.modal = node; }}>
  ...
</StyledModal>

Upvotes: 2

Related Questions