0

I'm new to react Js and try to understand how to do composition on data I obtained from different sources, via ajax (as explained here: Reactjs - loadResourcesFromServer - combine two sources).

I have a Comment object and an Author object.

var Author = React.createClass({
    ...
    render: function() {
        return (
            <div><a>{this.state.data.username}</a><img src="{this.state.data.picture}" /></div>
        );
    }
});

var Comment = React.createClass({
    ...
    render: function() {
        return (
            <div><p>{this.state.title}</p></div>
        );
    }
});

Calling < Author /> and < Comment /> return 2 separate divs, but I want to display something like

<div>
    <p>
        <img src="{this.state.data.picture}" />
        {this.state.title}, published by {this.state.data.username}
    </p> 
</div>

I tried to use a wrapper

<CommentWithAuthor>
    <Author/>
    <Comment/>
</CommentWithAuthor>

but can only access the props of the objects in this wrapper, not the objects themselves. I cannot use refs since I need a new renderer (React.js - access to component methods).

Any idea? Thanks!

Community
  • 1
  • 1
Raphael
  • 1,709
  • 2
  • 17
  • 27
  • I don't get what you are trying to achieve. Do you want to get data from a server (you receive an object containing comments with the author and the comment value? And you want to assign those values to Author and Comment correspondingly? Can you be a bit more specific? – rmuller Jun 05 '15 at 09:49
  • Hi rmuller, I try to mix the values of two ajax results in one object displaying html, ie
    user photo, comment title, published by username, read x times
    – Raphael Jun 05 '15 at 10:15

1 Answers1

1

You should use some hierarchy, for example, including comment block as part of author block , passing it the author id if you have more than one author and selecting the comment based on the author

var Author = React.createClass({
    ...
    render: function() {
        return (
            <div><img src="{this.state.data.picture}" />
                 <comment authoriid={this.props.id}/>
                 <a>{this.state.data.username}</a>
            </div>
        );
    }
});

that way you are sending down data from top level (author) to next level as intended by design in reactjs

arkoak
  • 2,437
  • 21
  • 35
  • Ok thanks arkoak, +1 for the hierarchy. An idea on how to do it if I have multiple elements of the comment to return, ie
    comment title, published by username, read x times
    ? thanks!
    – Raphael Jun 05 '15 at 10:14
  • please check this : http://stackoverflow.com/a/28320488/724913 , the jsfiddle has a data array which is used for looping and displaying all data. you will need to do the same with comments as your data array – arkoak Jun 05 '15 at 10:21