When I write this code, I expect my React Component to display nothing. However, it displays '0'. Why is this?
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
const object = {
array: []
}
return (
<>
{object.array && object.array.length && (
<p>Test</p>
)}
</>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
See this code sandbox for a live demo: https://codesandbox.io/s/sad-lovelace-mmrkz
React ignores boolean values by default, but does not ignore numbers.
Even if array is empty it is still a truthy value. If array.length equals to 0, the paragraph is not being rendered since 0 is a falsy value, but still it (array.length - 0) gets rendered because basically 0 is a number.
I would suggest you to evaluate array.length into a boolean value, so it won't get rendered.
{object.array && !!object.array.length && (
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With