dagda1 dagda1 - 3 months ago 33
React JSX Question

size element based on another element's dimensions in reactjs

Say I have an element like this:

export default class DemoAxis extends Component {
componentDidMount() {
const el = findDOMNode(this);

this.dimensions = getDimensionsFromNode(el);
}

render() {
const style = {
parent: {border: "1px solid #ccc", margin: "2%", maxWidth: "40%", padding: 10}
};

return (
<div ref="line">
<svg style={style} width={this.dimensions.width} height={this.dimensions.height}


I want to size the
svg
element based on the dimensions of the line element.

The element's dimensions will only be available in
componentDidMount
which is called after render.

I know I can call
setState
but that will cause a re-render and that might give me UI issues.

What is the best way of achieving this?

Answer

You can try react-dimensions

Wraps a react component and adds properties containerHeight and containerWidth. Useful for responsive design. Properties update on window resize. Note that the parent element must have either a height or a width, or nothing will be rendered

// ES2015
import React from 'react'
import Dimensions from 'react-dimensions'

class MyComponent extends React.Component {
  render() (
    <div
      containerWidth={this.props.containerWidth}
      containerHeight={this.props.containerHeight}
    >
    </div>
  )
}

export default Dimensions()(MyComponent) // Enhanced component