skpdm
skpdm

Reputation: 1438

Dealing with an empty array when using .map() in React

I have a React.JS component that will map the notes variable to display.

However, I have run into the problem of having no notes and receiving an error. What is a proper way to approach this?

Here is the code:

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;

Upvotes: 47

Views: 105861

Answers (4)

Anas Ben Yaiche
Anas Ben Yaiche

Reputation: 325

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

Upvotes: 16

justi
justi

Reputation: 4106

In your component, you can set the defaultProps property to set the initial value to your props:

static defaultProps = {
    items: []
};

Upvotes: 4

Dimitrij Agal
Dimitrij Agal

Reputation: 425

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.

Upvotes: 6

foundling
foundling

Reputation: 1756

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.

Upvotes: 49

Related Questions