React: how to compare current props.children with new one

compare, javascript, reactjs

Solution

You can make use of child `key` prop that React suggests that arrays of children should be given to uniquely identify them. Because each child has a key, you can reliably tell whether children has changed across prop changes (this is the entire point of keys!). If the keys don't match between new and old then they have changed.

React.render(<App><Child key='1'/><Child key='2'/></App>, document.body)

and do the check in the App component you want to check before each update if the children changed

shouldComponentUpdate(nextProps){
   var oldKeys = this.props.children.map( child => child.key);
   var newKeys = nextProps.children.map( child => child.key);

   //compare new and old keys to make sure they are the same
}

Note that this doesn't tell you if the content of each child has changed, you have to compare each by some criteria (such as deeply comparing props) if you want to know if nothing in the whole tree below this point has changed

as an even further optimization we know that children will never change as result of a state change so we can actually do our comparing in `componentWillReceiveProps()` and just set some state property like `childrenHaveChanged`

Problem

Hi, i am building component which acts only as wrapper for some other generated content and uses third party library. This library works with `props.children` of component. So far so good, but this thrird party library is little laggy when applied, or refreshed on element. And because only reason to refresh this library is when `props.children` changed I am trying to figure how to compare `this.props.children` and `nextProps.children` in `shouldComponentUpdate`. I was thinking that PureRenderMixin should do the work, but for me it does not works. Component is rerendered even if I change only `state.listName` as it is in example below. ``` <div> List name '{this.state.listName}' <br /> <MyComponent> <ul> {listOfLi} </ul> </MyComponent> </div> ``` Is there any way, how to manage comparing of `props.children` or any other option how to do something like that? Thanks for any help!

Original source