reactjsstate

Add element to a state React


I already have a state with this:

 this.setState({
      conversation:
          (
            <div>
              {conversation.map(element => {
                 if (element.id === this.props.id) {
                      return(
                        <div className="row msg_container base_sent">
                          <div className="col-md-10 col-xs-10">
                             <div className="messages msg_sent">
                                 <p>{element.message}</p>
                             </div>
                             </div>
                        </div>
                   )
             }
              else {
                 return(
                     <div className="row msg_container base_receive">
                        <div className="col-md-10 col-xs-10">
                          <div className="messages msg_receive">
                              <p>{element.message}</p>
                          </div>
                      </div>
                      </div>
                )
               }
             })}
           </div>
          )
       })

Now I would like to update it with new information. So add another div to it.

Something like that:

this.setState({conversation: previousConversation + new div})

How can I do it? Or I need to set a new state from zero


Solution

  • I don't think it's a good idea to store jsx components in the state of a component. I think you should only save the data in the state needed to render the component.

    If you really want to store jsx in the state, why won't you define your 'conversation' property as array? Then you'll be able to add new components to it.

    this.setState({
      conversation: [
            (<div>first</div)
      ]      
    });
    
    const currentConversation = state.conversation;
    currentConversation.push((<div>new div</div>));
    this.setState({conversation: currentConversation})
    

    But better to only store the data ie 'first' and 'new div'