Dealing with an empty array when using .map() in React
here is the simplest way to deal with
import React, {Component} from 'react';
class List extends Component {
constructor(props){
super(props);
}
render(){
var notes = this.props.items?.map((item, i)=>{
return(
<li className="listLink" key={i}>
<p>{item.title}</p>
<span>{item.content}</span>
</li>
)
});
return(
<div className='list'>
{notes}
</div>
);
}
}
export default List;
just try to add "?" for the array that you maped
If you want to render the notes when at least one note exists and a default view when there are no notes in the array, you can change your render function's return expression to this:
return(
<div className='list'>
{notes.length ? notes : <p>Default Markup</p>}
</div>
);
Since empty arrays in JavaScript are truthy, you need to check the array's length and not just the boolean value of an array.
Note that if your items
prop is ever null, that would cause an exception because you'd be calling map
on a null value. In this case, I'd recommend using Facebook's prop-types library to set items
to an empty array by default. That way, if items
doesn't get set, the component won't break.
In your component, you can set the defaultProps property to set the initial value to your props:
static defaultProps = {
items: []
};
You can just setting a fallback value for the this.props.item
render() {
const items = this.props.items || [] // if there's no items, give empty array
const notes = items.map((item, i) => {
return(
....
Doing .map()
on empty array will not produces an error, but will return an empty array. Which is fine because empty array is a renderable item in react and won't produce error in render()
and will not render the notes as there are no notes provided.