Button to close modal does not work

Asked

Viewed 150 times

0

Hello, I’m having a problem to make my modal button close, it opens through the header of the normal application.

I am using Reactjs 16.8 + Typescript 4.0.3.

// Header/index.tsx
import ContactForm from '../Contact';

import { Container, Contact } from './styles';

const Header: React.FC = () => {
  const [isContactVisible, setIsContactVisible] = useState(false);

  return (
    <Container>          
      <Contact onClick={() => setIsContactVisible(true)}>
        {isContactVisible ? (
          <ContactForm onClose={() => setIsContactVisible(false)} />
        ) : null}
        Contact
      </Contact>
    </Container>
  );
};

export default Header;

The code of the Modal:

// Modal//
import exitButton from '../../assets/exitButton.svg';

import { Container, Content } from './styles';

type Props = {
  onClose: any;
};

const Contact: React.FC<Props> = ({ onClose = () => {} }) => {
  return (
    <Container>
      <Content>
        <button type="button" onClick={onClose}>
          {console.log('Fechou! ', onClose)}
          <img src={exitButton} alt="Exit contact" />
        </button>
      </Content>
    </Container>
  );
};

export default Contact;

Console output when clicking, for once, at the button of header, and not the exit:

Captura de tela de 2020-11-28 21-52-08.png

The button to exit the modal does not work and nothing comes out of it on the console. How to make it work? I thank you already.

P.S.: I know there’s a React-modal library, but I’d like to do it without it, unless there’s no way out of this case.

1 answer

0


After 1 and a half day looking at the code and searching on Google, I found the error:

In the header/index.tsx i was putting the function inside the button, when the screen rendered the function rendered together and treated the modal as a button.

Before:

<Contact onClick={() => setIsContactVisible(true)}>
  {isContactVisible ? (
    <ContactForm onClose={() => setIsContactVisible(false)} />
  ) : null}
  Contact
</Contact>

Afterward:

<Contact onClick={() => setIsContactVisible(true)}>Contact</Contact>
{isContactVisible ? (
  <ContactForm onClose={() => setIsContactVisible(false)} />
) : null}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.