punjira
punjira

Reputation: 836

React get height of component

I need to know the height of a React Component inside another React component. I am aware that the height of an element can be reached by calling this.cmref.current.clientHeight. I'm looking for something like this:

child component:

const Comp = () =>{
    return(
        <div>some other stuff here</div>
    )
}
export default Comp

parent component:

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidSomething(){
        const height = this.compref.current.clientHeight;
        //which will be undefined
    }
    render(){
        return(
            <div>
                <Comp ref={this.compref} />
            </div>
        )
    }
}

Is this possible? Thanks in advance.

Upvotes: 0

Views: 1521

Answers (2)

Sree Nath
Sree Nath

Reputation: 543

const Comp = React.forwardRef((props, ref) => (
  <div ref={ref}> some other stuff here </div>
));

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    componentDidMount(){
        const height = this.compref.clientHeight;
        console.log("hieght", height);
    }
    render(){
        return(
            <div>
                <Comp ref={(el) => this.compref = el} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector("#app"))     

Could you try this way. Hope it helps. Please refer forward refs https://reactjs.org/docs/forwarding-refs.html

Upvotes: 1

ApplePearPerson
ApplePearPerson

Reputation: 4439

You'll need to actually ref the div of the child component in order to get the element you want instead of the child component itself. To do this you could pass a function to the child that the child then passes to the div. Working example below:

const Comp = (props) =>{
    return(
        <div ref={props.onRef}>some other stuff here</div>
    )
}

class App extends React.Component{
    constructor(props){
        super(props);
        this.compref = React.createRef();
    }
    
    componentDidMount(){
        const height = this.compref.current.clientHeight;
        //which will be undefined --- No more!
        console.log('height: ', height);
    }
    
    onCompRef = (ref) => {
      this.compref.current = ref;
    }
    
    render(){
        return(
            <div>
                <Comp onRef={this.onCompRef} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id='root' style='width: 100%; height: 100%'>
</div>

Upvotes: 2

Related Questions