Skip to content
Advertisement

ReactJS – prevent re-render children

I have parent React component with 3 children, like this:

var Parent = React.createClass({
   render: function() {
     return (<div>
         <C1/>
         <C2/>
         <C3/>
       </div>)
   }
})

I am trying to be able to change children’s position based on current parent state. So in different cases I need to return C1,C3,C2 or C3,C2,C1, etc. But I want to this without re-render the children. I am trying to use shouldComponentUpdate on each of the children but its gets called for the components that didn’t change their position within parent’s render method. So if initially return C1, C2, C3 then C2, C1, C3 then shouldComponentUpdate gets called for C3 but not for C1 or C2 so in this case I can return false inside C3 and prevent re-render but I don’t understand why shouldComponentUpdate is not called for the children that did change their position.

Any suggestions? thank you.

Advertisement

Answer

Take a look at https://reactjs.org/docs/fragments.html#keyed-fragments.
Keyed fragments were designed to solve theses kind of problem 😉

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement