0

I would like to create a dynamic width React container to contain dynamic width children.

The dynamic width React container is that, with min-width 100px and max-width 300px. It could contain many children depend on the width of each child.

eg. If it contains one child with width 120px, the width of the container should be 120px.

If the width of the first child is 300px, it could only contain this child.

If the width of the first child is 200px, and the second is 100px, it could only contain first and second children.

If the width of the first child is 200px, and the second is 50px, could it contain a new child? That depends on the width of the third child. If its width is greater than 50px, it couldn't be contained.

I use the React functional component to do it. The key point is how to measure the children's width in advance.

See my workable demo.

Does
  • 569
  • 6
  • 24
  • why are you not taking the width of the margins into the account , in your code then? – Shiva Sai Aug 28 '20 at 06:55
  • I see you have imported `useRef`, `useEffect`, and `useState` within your Container.js, but they are not being used. You could set your child `` tags to have a ref, then using `useEffect` hook to add the width of your current child to childWidth state (using `useState`). In order to measure the width of your child, you can use `.current.offsetWidth` – Alfred Aug 28 '20 at 07:21
  • @ShivaSai Of course, the margin should be taken into the account. That't not the key point of my issue. So I didn't clarify it clearly. – Does Aug 28 '20 at 07:39
  • @Alfred I forked other guy's demo. Would you like to finish this demo as my requirement in order to accept your answer. – Does Aug 28 '20 at 07:42
  • 1
    @Does i have made a small codepen https://codepen.io/ssarapu/pen/mdPmgQB?editors=1100, can you see if this is what you wanted.. no javascript. only css and html – Shiva Sai Aug 28 '20 at 08:04
  • @ShivaSai Thanks for you demo. It's really a pure css solution. I'm expecting a React solution. If the width of more children could't be contained, I expect it's better not to append them into DOM. – Does Aug 28 '20 at 08:16
  • my dear brother. but you can't get the width or height of the element before even render. https://stackoverflow.com/questions/49058890/how-to-get-a-react-components-size-height-width-before-render your solution is good – Shiva Sai Aug 28 '20 at 08:30
  • @ShivaSai I use `flex-wrap:wrap;overflow:hidden;` but I still expect to count the number of hidden elements to show. So I think this css solution can't resolve my issue. – Does Aug 29 '20 at 03:28

0 Answers0