2
\$\begingroup\$

I am rendering a list from an array of objects. I want to check the correctness of the array before rendering. For that I am using typeof and null.

In real situation the list comes from the API.

Is it the correct way? and is there any better way to do it?

const activeEvents = [{
  id: '1',
  title: 'event 1'
}, {
  id: '2',
  title: 'event 2'
}]

function App() {
  return ( <div >
      <h4> List </h4> 
      { typeof activeEvents === 'object' &&
      activeEvents !== null &&
      activeEvents.map(event => ( 
        <li key = { event.id } value = { event.id } > { event.title } 
        </li>
       ))} 
      </div>
);
}

ReactDOM.render( <
  App / > ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root" />

\$\endgroup\$
4
\$\begingroup\$

typeof activeEvents === 'object' && activeEvents !== null can be true for both Array and Object :

const array = [];
const obj = {};

console.log(typeof array === 'object' && array !== null)
console.log(typeof obj === 'object' && obj !== null)

you can use Array.isArray

const activeEvents = [{
  id: '1',
  title: 'event 1'
}, {
  id: '2',
  title: 'event 2'
}]

function App() {
  return ( 
    <div >
      <h4> List </h4> 
      { Array.isArray(activeEvents) && 
        activeEvents.map(event => ( 
          <li key = { event.id } value = { event.id } > { event.title } </li>
        ))
      } 
    </div>
  );
}

ReactDOM.render( <
  App / > ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root" />

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.