Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this React component return the string '0'

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

like image 261
ubi Avatar asked Dec 06 '25 05:12

ubi


1 Answers

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 && (
like image 100
kind user Avatar answered Dec 08 '25 18:12

kind user