dev
dev

Reputation: 1

Simultaneously accessing two arrays in react

I have this portion of code mentioned below, 'msg' and 'botMsg' are two different array of objects. Let say the dummy content of 'msg' and 'botMsg' be:

 msg : [ {id: 1, content: 'hello' }, {id: 2, content: 'world'} ]
 botMsg : [{id: 3 content: 'yes'}, {id: 6, content: 'hii'} ]

Given both the arrays are of equal length how can i display 'botMsg' content in the second span tag mentioned. i want to alternatively display the 'botMsg' content after every 'msg' content (which i have displayed in first span tag).

const Msg = ({ msg, botMsg }) => { 

    const msgList = msg.length ? (
    msg.map((i,j) => {
        return(
            <span>
            <div key={i.id}>
                <span>{i.content}</span>
            </div>
            <div key={i.id}>
                <span>{}</span>
            </div>
            </span> 
        )
    })
) : (
    <p className="center">you have no msg yet</p>
)

}

so the kind of output i expect is

hello
yes
world
hii

Upvotes: 0

Views: 505

Answers (1)

Tholle
Tholle

Reputation: 112917

The second argument given to the function given to map (j in your code example) is the index of the current element, so you can use that to access the right element in the botMsg array.

Example

class App extends React.Component {
  state = {
    msg: [{ id: 1, content: "hello" }, { id: 2, content: "world" }],
    botMsg: [{ id: 3, content: "yes" }, { id: 6, content: "hii" }]
  };

  render() {
    const { msg, botMsg } = this.state;

    return (
      <div>
        {msg.map((i, j) => {
          return (
            <span key={i.id}>
              <div>
                <span>{i.content}</span>
              </div>
              <div>
                <span>{botMsg[j].content}</span>
              </div>
            </span>
          );
        })}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 2

Related Questions