0

I've encountered a problem with rendering some elements in React. (I use ImmutableJS)

renderComponents: function(components) {
    if(components.isEmpty()) return [];

    var table = [];

    components.map(function(component) {
      table.push(<ComponentTableElement key={ component.get('id') } data={ component } />);

      if(component.has('children')) {
        var children = component.get('children');
        table.concat(this.renderComponents(children));
      }
    });

    return table;
  },

As I looked for error, I found that this.renderComponents(children) doesn't return anything at all and the code somehow stops.

I mean before that line everything works ok, but then after this line, when i try to console.log something, it doesn't show up. And it doesn't even reach return table.

So what is wrong with that code?

1 Answer 1

2

In the context of the function you pass to map, this refers to the window object, not to the current component instance, so this.renderComponents is undefined when you try to call it.

components.map(function(component) {
  this === window;
});

You can pass a value to use as this in the body of your function as the second parameter of Array::map.

components.map(function(component) {
  table.push(<ComponentTableElement key={ component.get('id') } data={ component } />);

  if(component.has('children')) {
    var children = component.get('children');
    // here, `this` refers to the component instance
    table.concat(this.renderComponents(children));
  }
}, this);

If you're using ES6, you can also use fat-arrow functions, which are automatically bound to this.

components.map((component) => {
  table.push(<ComponentTableElement key={ component.get('id') } data={ component } />);

  if(component.has('children')) {
    var children = component.get('children');
    // here, `this` refers to the component instance
    table.concat(this.renderComponents(children));
  }
});
Sign up to request clarification or add additional context in comments.

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.