dagda1 dagda1 - 1 year ago 141
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
element based on the dimensions of the line element.

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

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

What is the best way of achieving this?

Answer Source

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() (

export default Dimensions()(MyComponent) // Enhanced component
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download