How to get horizontal size from DOM?

I have a complex web page using React components, and I'm trying to convert a page from a static layout to a more responsive, resizable one. However, I constantly run into limitations with React, and I wonder if there is a standard template to solve these problems. In my specific case, I have a component that displays as a div with the display: table-cell and width: auto.

Unfortunately, I cannot ask for the width of my component because you cannot calculate the size of an element unless it is actually placed in the DOM (which has the full context with which you can display the actual rendered width). Besides using this for things like relative mouse positioning, I also need this to set width attributes correctly on SVG elements in the component.

Also, when a window is resized, how do I report resize from one component to another during installation? We do all our third-party SVG rendering in shouldComponentUpdate, but you cannot set state or properties on yourself or on other child components in this method.

Is there a standard way to solve this problem with React?

+4
source share
2 answers

The lifecycle method that you probably want is componentDidMount
Elements are already placed in the DOM, and you can get information about them from component links.

Example:

var Container = React.createComponent({

  componentDidMount: function () {
    var width = this.refs.svg.getDOMNode().offsetWidth;
  },

  render: function () {
    <svg ref="svg" />
  }

});
+1
source

In componentDidMount you can get window.width or ReactDom.findDOMNode (this) .width. Then use the width in the state and go as a support as needed. You can also set a listener for the resize event.

0
source

Source: https://habr.com/ru/post/1614283/


All Articles