0

I have a reactjs class called MyDictionary that renders data that a python file sends in. This class returns a dictionary structure. I want to access only a couple of elements from MyDictionary via a separate class, and a different set of elements also from MyDictionary, via a separate class. I tried React.createElement(SomeOtherClass, { as shown below, but this doesn't work... what am I missing?

class MyDictionary extends React.Component {
render() {
  return this.props.results.map((result, index) =>
    React.createElement(
      "div",
      { className: "col-sm-12" },
      React.createElement(SomeOtherClass, {
        key: result.id,
        name: result.name,
        index: result.index,
        activity: this.props.index + 1,
        images: this.props.image_labels
      })
    )
  );
 }
}
return MyDictionary;

1 Answers1

0

Looks like your this operator inside the callback function is not what you expect.

The easiest way to resolve this is to create a var to this before your map call.

var _this = this;

Then use _this instead of this inside your callback.

You should also read up on javascript closures.

Edit: render() should return one root element.

class MyDictionary extends React.Component {
  render() {
    var _this = this;
    var children = this.props.results.map((result, index) =>
      React.createElement(
        "div",
        { className: "col-sm-12" },
        React.createElement(SomeOtherClass, {
          key: result.id,
          name: result.name,
          index: result.index,
          activity: _this.props.index + 1, // using _this
          images: _this.props.image_labels // using _this
        })
      )
    );
    return React.createElement("div", null, children);
  }
}
return MyDictionary;
Lian
  • 2,197
  • 2
  • 15
  • 16
  • So `React.createElement(SomeOtherClass, {` is the right way to link to multiple classes? – Gorgorita32 Gorgorita Apr 28 '18 at 21:04
  • I did not notice this before, you need to also wrap your element inside one element, like a
    .You are basically nesting `SomeOtherClass` inside your `MyDictionary` element. If it makes sense, then it should be fine. (If you think in terms of HTML elements, MyDictionary is a
    that contains multiple elements.
    – Lian Apr 28 '18 at 21:17
  • Ok, this is helpul, ty. I guess the question that still stands is... can I access the values of the children from MyDictionary and render them through another class? Or multiple classes? How would I do that? I'm pretty lost and I've been trying to figure this out for days... – Gorgorita32 Gorgorita Apr 28 '18 at 22:08
  • like... why can't the elements be accessed thorough MyDictionary.this.props.children? – Gorgorita32 Gorgorita Apr 28 '18 at 22:26
  • Here's a good answer to what I think you need: https://stackoverflow.com/questions/21285923/reactjs-two-components-communicating – Lian Apr 29 '18 at 12:55