Question: Get the size of a react component?

Question

Get the size of a react component?

Answers 1
Added at 2016-12-27 12:12
Tags
Question

I know that I can do this:

<div ref='container' />

and then

this.refs.container.getBoundingClientRect()

but I can't do this

import Thumbnail from 'react-bootstrap/lib/Thumbnail'
<Thumbnail ref='thumbnail' />
this.refs.thumbnail.getBoundingClientRect()

because this.refs.thumbnail won't return a HTML object. How can I get the size of thumbnail?

Answers to

Get the size of a react component?

nr: #1 dodano: 2016-12-27 14:12

One dirty way to do this, making the component have a ref for the wrapping element and setting the size via a function type prop.

Below I have implemented as an example, as your need varies, you might change the implementation.

class ComponentWhichNeedsInfo extends Component {

 constructor(props){
  super(props)
  this.state = { sizes : {} }
  this.setSize = this.setSize.bind(this)
 }

 setSize( elUniqueName, size ){
   this.setState({ sizes[elUniqueName] : size })
 }

 render(){
   return (
     <div>
       <Thumbnail 
         uniqueName="thumbnail1"
         setSize={this.setSize}
       />
     </div>
   )
 } 

}

class Thumbnail extends Component {
 static propTypes = {
  setSize : PropTypes.func,
  uniqueName : PropTypes.string
 }
 componentDidMount(){
  let { setSize } = this.props
  if( this.props.setSize ){
    let { uniqueName } = this.props
    setSize( uniqueName, this.parentNodeEl.getBoundingClientRect() )
  }
 }
 render(){
   return (
     <div ref={ node => { this.parentNodeEl = node } } >
       ...
     </div>
   )
 } 

}

Even better, you might instead give your elements ref to parent element instead of the size.

Source Show
◀ Wstecz