user4773422
user4773422

Reputation: 75

ReactJS display two arrays with mapping

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?

Upvotes: 1

Views: 3385

Answers (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>
            )

    }

});

Upvotes: 1

Related Questions