Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS get rendered component height

Tags:

reactjs

I'm attempting to integrate or create a React version of https://github.com/kumailht/gridforms, to do so I need to normalize the height of the columns inside of the row. The original takes the height of the grid row and applies it to the children columns.

I had planned to get the height of the row and then map it to a property of the child, though from my attempts I'm thinking this might not be the ideal way or even possible?

Below is my current code.

GridRow = React.createClass({   render(){         const children = _.map(this.props.children, child => {             child.props.height = // somehow get row component height             return child         })     return (<div data-row-span={this.props.span} {...this.props}>       {children}     </div>)   } })  GridCol = React.createClass({   render(){     return (<div data-field-span={this.props.span} style={{height:this.props.height}} {...this.props}>       {this.props.children}     </div>)   } }) 

I tested setting the style this way and it will work, however getting the height isn't.

EDIT: Fiddle:

https://jsfiddle.net/4wm5bffn/2/

like image 940
Patrick Cauley Avatar asked Jul 27 '15 19:07

Patrick Cauley


People also ask

How do you find the parent width in React?

To get the parent height and width in React: Set the ref prop on the element. In the useEffect hook, update the state variables for the height and width. Use the offsetHeight and offsetWidth properties to get the height and width of the element.


2 Answers

A bit late with the answer but technically you can get element hight this way:

var node = ReactDOM.findDOMNode(this.refs[ref-name]); if (node){   var calculatedHeight = node.clientHeight; } 
like image 198
anyab Avatar answered Oct 04 '22 06:10

anyab


According to current React docs, the preferred use of refs is to pass it a callback rather than a string to be accessed elsewhere in this.refs. So to get the height of a div (within a React.Component class):

componentDidMount() {   this.setState({ elementHeight: this.divRef.clientHeight }); }  render() {   return <div ref={element => this.divRef = element}></div> } 

Or it works this way, though I don't know if this is advisable since we set state in the render method.

getHeight(element) {   if (element && !this.state.elementHeight) { // need to check that we haven't already set the height or we'll create an infinite render loop     this.setState({ elementHeight: element.clientHeight });   } }  render() {   return <div ref={this.getHeight}></div>; } 

Reference: https://facebook.github.io/react/docs/more-about-refs.html

like image 43
Andy_D Avatar answered Oct 04 '22 06:10

Andy_D