5

I want to loop an array and create list items out of it. In the console,it is showing mistake is thrown, because my array has no keys but only values. So What is the right operation to read out an array?

*// this.props.items = ["cars","streets","houses"];*Wrong. You can't update props

var TodoList = React.createClass({
 render: function() {
  var createItem = function(item) {
  return <li>{item}</li>;
  };
  return <ul>{this.props.items.map(createItem)}</ul>;
}
});
1

2 Answers 2

9

Try this way:

this.filterOptions =['Monthly','Weekly','Daily'];

   <ul>
       {  this.filterOptions.map((filterItem) => {
       return (
                <li key={filterItem}>
                    <span>{filterItem}</span>
                 </li>
              );
          })
       }
     </ul>

EDIT 1: If there is duplicate value in array,

   <ul>
       {  this.filterOptions.map((filterItem,index) => {
       return (
                <li key={index}>//key must be uniq
                    <span>{filterItem}</span>
                 </li>
              );
          })
       }
     </ul> 
Sign up to request clarification or add additional context in comments.

4 Comments

You could also do .map((filterItem, i) => { return (<li key={i}> ...
@Chris yes. It will be useful when we have duplicate value.
Is there a missing closing brackets ((filterItem,index) ?
No. it is closed after return.
1

Just to clarify because i see u use:

  var TodoList = React.createClass({

instead of

class TodoList extends React.Component {

and the question about the closing brackets in the comments above: "Is there a missing closing brackets ((filterItem,index)""

i assume you are not using the es6 syntax, so i wanted to point out that

{ this.filterOptions.map(function(filterItem, index) {
    return (
      <li key={index}>
          <span>{filterItem}</span>
       </li>
    )
  }, this)
}

equals

{ this.filterOptions.map((filterItem,index) => {
   return (
      <li key={index}>
          <span>{filterItem}</span>
       </li>
    );
  })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.