Kevin Kevin - 1 month ago 10
React JSX Question

iterate through undefined/null objects in a react element

I have a super simple react element like this below:

const Stores = ({ stores }) => {
const renderStores = () => Object.keys(stores).map(store => {
return (
<div key={store}>
{ store }
</div>
)
})

return (
<div>
{ renderStores() }
</div>
)
}


It takes in
stores
(it's a POJO, not an array) as a prop and iterates through its keys to display the name of the store.

The problem is when I write react elements this way, the
stores
isn't defined or could be null at this point in my app and this causes
Object.keys

to throw an error because you can't iterate through undefined or null.

What I want is the behavior of this react component to render nothing if
stores
is undefined or null.

I would like to avoid the need to wrap my
renderStores
function and check for undefined/null:

const Stores = ({ stores }) => {
const renderStores = () => {
if (stores) {
return Object.keys(stores).map(store => {
return (
<div key={store}>
{ store }
</div>
)
})
} else {
return <div></div>
}
}

return (
<div>
{ renderStores() }
</div>
)
}


But this isn't easy on the eyes.

I could instead do this:

return (
<div>
{ stores ? renderStores() : '' }
</div>
)


But this seems like boilerplate.

Is there a better way or a common convention to protect
Object.keys()
from throwing an error when undefined/null is passed in to be iterated in a react element?

Answer

If stores is null or undefined, it's falsy, and you could use a logical OR to just use an empty object instead, which would have no keys, an no iteration would happen

Object.keys(stores||{}).map(...

you wouldn't get an empty element though, you'd need a condition for that