1

I have two arrays. The i'th element from both arrays form one component. I want to render multiple components like this in a list. Here's the code

var ShowData = React.createClass({
        render:function(){
            var itemNames = this.props.names.map(function(item){
                return <div>{item}</div>;
            });
            var itemDesc = this.props.contents.map(function(description){
                return <p>{description}</p>;
            });

            return(
                <div>
                <h3> {itemNames}</h3>
                <div>{itemDesc}</div>
                </div>
                )

        }

    });

Here's my render function

<ShowData names = {this.state.items} contents = {this.state.desc} />

It displays the entire first array and then the entire second array. What gives?

1 Answer 1

1

If the arrays have the same order can you do it like this(Not tested).

var ShowData = React.createClass({
    render:function(){
        var self = this;
        var items = this.props.names.map(function(item, key){
            return (<div>
                         <h3>{item}</h3> 
                         <div>{self.props.contents[key]}</div>
                    </div>);
        });
        return(
            <div>
                 {items}
            </div>
            )

    }

});
Sign up to request clarification or add additional context in comments.

3 Comments

Just to add to your answer that passing two pieces of clearly related data like item and description as separate arrays is kind of terrible. They should be passed to the component as an array of {item: x, description: y} elements instead. Two arrays and indexing like this is just asking for trouble if they ever end up not being exactly equal lists with the correct corresponding indexes between the two.
@MikeDriver you are right.. and should tell this to the question author
@MikeDriver I realised that after I got my code working thanks to Jonatan. Now changed it to a single JSON object. Thanks guys !

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.