How do I return my modal to the screen? I’m using Reactjs

Asked

Viewed 25 times

-2

I have a button that changes the visibility of my modal and puts as true, after that the intention was to show the modal on screen as if it was an Alert.

const Cadastro = () => {
  let history = useHistory();

  const [ isModalVisibel, setIsModalVisible ] = useState(false);

  function login({ username, user, password, selectOption, selectOptionMonth, selectOptionYear }) {
    const data_aniversario =
      selectOption + "/" + selectOptionMonth + "/" + selectOptionYear;
    const dados = {
      nome_pessoa: username,
      data_nascimento: data_aniversario,
      email: user,
      senha: password,
    };

    console.log(dados.nome_pessoa);
    return(
      <div>
        {isModalVisibel 
        ? <Modal onClose={() => setIsModalVisible(false)}>
            <h1>Janela de informações</h1>
          </Modal>
        : null
        }
      </div>
    )

Below I’ll leave the way I’m using the button. NOTE: The button is inside a form

<button onClick={() => setIsModalVisible(true)} type="submit">Cadastrar</button>

1 answer

0


You should pass isModalVisibel as props for Component Modal and do this validation inside the component. Now the button with the function setIsModalVisible(true) should be called within the context of the login component (I don’t know where it is rendering the button exactly).

Probably the isModalVisibel is not changing the value.

const Modal = ({ show, onClose }) => (
  show && (
    <div>
      <h1>Modal está aberto</h1>
      <button onClick={onClose}>x</button>
    </div>
  )
)

const Cadastro = () => {
  const [isModalVisibel, setIsModalVisible] = useState(false);

    return (
      <div>
        <Modal show={isModalVisibel} onClose={() => setIsModalVisible(false)}>
          <h1>Janela de informações</h1>
        </Modal>
        <button onClick={() => setIsModalVisible(true)}>Abrir Modal</button>
      </div>
    );
  }
};

Browser other questions tagged

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