React - how to get the size of component children and resize them

I have a component that arranges elements in a dynamic grid, something like this:

class GridComponent extends React.Component { render() { return <div> {items.map(function(item){ return <ItemComponent someData={item}/>; })} </div> } } 

Now I want to place ItemComponents based on some algorithm that needs separate dimensions of ItemComponents .

So, I think I need:

  • Render all ItemComponents
  • Get the sizes of all ItemComponents (which are fixed only after their rendering)
  • Move ItemComponents based on my algorithm

So my question is how to do this, or more specifically:

  • How to execute code when all ItemComponents were displayed?
  • How to get ItemComponents sizes from GridComponent?
  • Do I have to repeat the GridComponent with the calculated position of ItemComponents or do I need to somehow directly set the position of ItemComponents ?
+6
source share
1 answer

This is a pretty cool idea, and you can do it completely using the internal state and several React life cycle methods. To answer each of your questions:

  • componentDidMount will be called by the parent after all the constructors and componentDidMount each child, so there is a good place to call some function, which may depend on your state.
  • by size I ItemComponent you mean the width and height of the screen of the root component of ItemComponent , so on componentDidMount in ItemComponent you can set ref and find the width and height of the DOM element
  • the best solution would be to set but not display the child elements (can be done with some initialization state variable or support) and display them only after you have calculated your true end positions. For example, each ItemComponent may have a pointer called initialized , which is false until the parent finds where to put it.

Putting it all together, since your algorithm will probably need all the dimensions to work, most likely you want to create a callback in your parent, call it setItemDimensions(id, width, height) , which is called in componentDidMount for each ItemComponent . You must store a map of all your initialized ItemComponent and each time setItemDimensions is setItemDimensions , check if there are any remaining ones (maybe initialize the map with all zeros and assume that it is β€œready” when there are no zeros on the left).

Once the last null disappeared, you can run the algorithm, find out the positions and display the ItemComponent in the right place and using initialized={true} (or just initialized ).

Let's see if this works!

+6
source

All Articles