faliraki33
faliraki33

Reputation: 1

How do I render one of several of the same react component?

I dont know if my brain is extra mushy today or what. Im trying to learn react and now I have a list of messages that is rendered from an array. Inside every message I have a button to render the "send message" component to answer the message. My problem is that when I press the button "answer", All the message-items in the list renders the 'send message' component. How do I bind it to just one message I clicked answer in? See my code and you will understand my question:

render() {
let messages = this.state.messages.map((item, key) =>
  <div>
    <ul key={item.id} className="messageList">
      <li><h3 className="messageTitle">{item.title}</h3></li>
      <li>{item.message}</li>
      <li className="messageSignature">from: {item.from}</li>
    </ul>
    {this.state.showSendMessage ? <SendMessage recipient={item.from} title={item.title}></SendMessage> : null}
    <button onClick={this.toggleShowSendMsg.bind(this)}>Answer</button>
  </div>
);

Upvotes: 0

Views: 27

Answers (1)

d-saurabh
d-saurabh

Reputation: 246

Its because your state variable "showSendMessage" is not unique to any particular message and hence its becoming true for all the elements of messages.

Add one more state variable as "key".

render() {
let messages = this.state.messages.map((item, key) =>
  <div>
    <ul key={item.id} className="messageList">
      <li><h3 className="messageTitle">{item.title}</h3></li>
      <li>{item.message}</li>
      <li className="messageSignature">from: {item.from}</li>
    </ul>
    {this.state.showSendMessage && this.state.key == key ? <SendMessage recipient={item.from} title={item.title}></SendMessage> : null}
    <button onClick={this.toggleShowSendMsg.bind(key)}>Answer</button>
  </div>
);

and change the state of key in your toggleShowSendMsg method the way you are doing for showSendMessage.

Upvotes: 1

Related Questions