I have a query, I'm working on a project in React 17 and Next 12, and there is a way to validate that an object is not null
in a way that I didn't know, something like:
miObjeto?.objetoInterior?.propiedad = value
This avoids doing things likeif(miObjeto && miObjeto.objetoInterior) {...}
I first thought it was a JS feature, but when I tried it in a Vue project it threw errors.
Now, I want to make a function like this:
useEffect(() => {
const body = document.querySelector("body") || null;
if (mobileMapState === 3) {
handleOpenMap();
body.style.overflow = "hidden";
} else {
body.style.overflow = "auto";
}
}, [mobileMapState]);
And it happens to me that I want to make sure that body
it is not null
before doing body.style.overflow = "hidden";
, for what I am trying to do
body?.style?.overflow = "hidden";
And I get an error from Eslint:
Parsing error: Invalid left-hand side in assignment expression.
so i try
body && body.style.overflow = "hidden";
But the error is the same.
The only way I found to do this was:
if (body) {
body.style.overflow = "hidden";
}
And although it works, I have doubts, such as why I can't use it ?
in this case, and if there was a correct way to use it to make the validation shorter.
Thank you very much
It is known as optional chaining.
And what it does is simplify access to values by returning null or undefined if it doesn't exist, instead of reporting an error.
It is also more readable than the short circuit operator.
Reference: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Now for deactivating that line
Or directly in the config.
Reference:
https://eslint.org/docs/latest/rules/no-unused-expressions