score:7

Accepted answer

your codepen is alomost fine, only thing you missed is proper key for message component,

for react to render components properly each component should have different key, so i changed the piece of code from

<Messages style="me" msg={this.state.chat} key={this.state.chat} sent={(this.state.sent[this.count])?this.state.sent[this.count]:''} />

To

<Messages style="me" msg={this.state.chat} key={this.count} sent={(this.state.sent[this.count])?this.state.sent[this.count]:''} />

and code-pen worked fine

EDIT this solves the propblem

instead of saving the components to state, dynamically build them. check this codepen.io/abhirathore2006/pen/JbjjPx

score:0

componentWillReceiveProps should take nextProps.

score:0

Whenever the whole component rerenders, React matches all the components with the previous state/key. So if you give a unique key to the child on every time parent rerenders, the child will also re-render.

Lodash provides a function _.uniqueId() that generates a unique id every time it is called.

<Parent>
    <Child key={_.uniqueId('child_component')} />
</Parent>

score:1

Use this as a key for component

 this.state.messages.length

React won't allow you to enter two elements with the same key. This is how the react virtual DOM diffs the changes on re-render


Related Query

More Query from same tag