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?