Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX: Iterating through a hash and returning JSX elements for each key

I'm trying to iterate through all the keys in a hash, but no output is returned from the loop. console.log() outputs as expected. Any idea why the JSX isn't returned and outputted correct?

var DynamicForm = React.createClass({
  getInitialState: function() {
    var items = {};
    items[1] = { name: '', populate_at: '', same_as: '', 
                 autocomplete_from: '', title: '' };
    items[2] = { name: '', populate_at: '', same_as: '', 
                 autocomplete_from: '', title: '' };
    return {  items  };
  },



  render: function() {
    return (
      <div>
      // {this.state.items.map(function(object, i){
      //  ^ This worked previously when items was an array.
        { Object.keys(this.state.items).forEach(function (key) {
          console.log('key: ', key);  // Returns key: 1 and key: 2
          return (
            <div>
              <FieldName/>
              <PopulateAtCheckboxes populate_at={data.populate_at} />
            </div>
            );
        }, this)}
        <button onClick={this.newFieldEntry}>Create a new field</button>
        <button onClick={this.saveAndContinue}>Save and Continue</button>
      </div>
    );
  }
like image 652
martins Avatar asked Apr 09 '15 09:04

martins


People also ask

Can you nest JSX elements into another JSX element?

You can nest JSX elements inside of other JSX elements, just like in HTML.

How do you iterate in JSX?

Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.

Can I use forEach in JSX?

forEach method can be used when you need to call a function for every element in an array. However, forEach() can't be used to iterate over an array directly in your JSX code.

How do you loop through an object in React JSX?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.


2 Answers

Object.keys(this.state.items).forEach(function (key) {

Array.prototype.forEach() doesn't return anything - use .map() instead:

Object.keys(this.state.items).map(function (key) {
  var item = this.state.items[key]
  // ...
like image 98
Jonny Buchanan Avatar answered Oct 17 '22 13:10

Jonny Buchanan


a shortcut would be:

Object.values(this.state.items).map({
  name,
  populate_at,
  same_as,
  autocomplete_from,
  title
} => <div key={name}>
        <FieldName/>
        <PopulateAtCheckboxes populate_at={data.populate_at} />
     </div>);
like image 39
Olivier Pichou Avatar answered Oct 17 '22 13:10

Olivier Pichou