0

I want to recovery the DOM.offsetWidth of all childrens. All of them have different sizes, and depends of style theme based on css.

Everything works fine on ComponentDidUpdate() method, but this is not triggered at first time.

I Can not put all the code, but below the example code, so:

  • How to wait to all childrens? or
  • How to tell to parent: All DOM is ready, now check the size

Example Parent

class Parent extends Component {
  this.childDOMRef = null;

  setChildDom(element) {
    this.childDOMRef = element;
  }

  componentDidMount(){
    const childrenWidth = [...this.childDOMRef.children]
    .reduce((prev, current) => prev + current.offsetWidth, 0);

    console.log(childrenWidth); // :( it is 0 on DidMount
  }


  render(){
    return <ChildStateLess
      items={this.props.items}  // I receive from redux
      setInnerRef={this.setChildDom}
    >
  }
}

Example Child (stateless)

const ChildStateLess = ({setInnerRef, items}) => { 
    <div ref={setInnerRef}>
      { items.map(item) => (<div>{item}</div>)}
    </div>
};

/// UPDATE

OnDidMount obviously the child items does not exist.

OnDidUpdate all exists, but this method is not triggeren on enter to web.

enter image description here

/// UPDATE 2

Keep a number reference, for last rendered, does not work as expected can not get DOM property

enter image description here

elporfirio
  • 306
  • 2
  • 15
  • why do you have not returned the ChildStateLess component in the render()? – Pouya Jabbarisani Sep 05 '18 at 16:24
  • sorry, miss that, now updated. – elporfirio Sep 05 '18 at 16:28
  • Possible duplicate of [React props.children width](https://stackoverflow.com/questions/42319191/react-props-children-width) – Chris Cousins Sep 05 '18 at 16:29
  • This is probably is not the best answer but you can use react 'context' in your child component's componentDidMount() so you can determine is child component mounted or not in your parent component. – Pouya Jabbarisani Sep 05 '18 at 16:32
  • @PouyaJabbarisani on every change we will create a lot of new context, it is not? :/ – elporfirio Sep 05 '18 at 16:43
  • No, universal is something like a universal state and data flow as a built-in feature in react. and you can set the mount status of your child component and check it in parent component before then getting the width. – Pouya Jabbarisani Sep 05 '18 at 16:47
  • @PouyaJabbarisani does not work, when the quantity === items.length, they only exist on virtual DOM, so the real **width** does not exist or is equal to `0`. – elporfirio Sep 05 '18 at 16:53

0 Answers0