0
My expectation: create a button that opens a modal for the user to enter information and this information turns a card to be shown on screen.
The problem: I made an example in Codesandbox that exemplifies well my problem, although not exactly my scenario: https://codesandbox.io/s/ecstatic-pike-p9kud?fontsize=14&hidenavigation=1&theme=dark
If you open the modal and then press on close everything goes well. But by clicking outside the modal or even inside it, an error is thrown on the screen (cannot read Property "" of Undefined). In my head, if a condition is of the falsy type, the JS simply jumps to the next condition. But that’s not what’s happening. JS (or React) is "demanding" that all conditions are Truthy so that it continues to meet the conditions.
Follow my real code:
const [modalStatus, setModalStatus] = React.useState(false);
React.useEffect(() => {
// o estado modalStatus é alterado para true ao clicar em um botão que abre o modal
if (modalStatus) {
const modalClick = (event) => {
// aqui, todas as tags que envolvem o clique do usuário são capturadas
const clickPathElements = [...event.path];
// a função abaixo retorna um objeto contendo o nome de todas tags (chave) e o id e class
// (valores)
const getElementsAttributes = clickPathElements.reduce((prev, cur) => {
if (cur.id || cur.classList) {
const [curId, curClass] = [cur.id, cur.classList[0]];
return {
...prev,
[cur.tagName.toLowerCase()]: { id: curId, class: curClass },
};
}
return prev;
}, {});
// aqui começa o malabarismo mental
// se o clique não for no modal, o valor da div (que é o elemento que segura o modal) é undefined
// e o modal é fechado
if (getElementsAttributes.div === undefined) {
setModalStatus(!modalStatus);
}
// se o clique foi no botão fechar o modal e o valor da div não for undefined, o modal é fechado
else if (
getElementsAttributes.button.id === "close" &&
getElementsAttributes.div !== undefined
) {
setModalStatus(!modalStatus);
}
// por fim, se o clique foi na div e não foi no botão de fechar, ou seja, o clique foi no modal, ele
// continua aberto
else if (
getElementsAttributes.div !== undefined &&
getElementsAttributes.button === undefined
) {
console.log("funciona");
}
};
window.addEventListener("click", modalClick);
return () => window.removeEventListener("click", modalClick);
}
}, [modalStatus]);
The above code works only if it is in this exact order. If the third Else if is in place of the second Else if, the same error as the codesandbox example is returned.
The problem is that you are trying to access properties of
undefined
, which causes an error in Javascript. In most cases, trying to access a value of a non-existent object makes no sense. However, you can use the optional chaining in this case (when trying to access some property of an object that may be nullish).– Luiz Felipe
@Luizfelipe Cara, no words. Thank you very much. You managed to help me solve the problem. If you want to create an answer, I will gladly mark it as correct.
– Ricardo Passos