user6620828
user6620828

Reputation:

How to get the height of an element in reactjs?

How to get the height of an element in reactjs for use it in a style of another element ?

What is wrong in my code ?

import React, { Component } from 'react';

import TextField from 'material-ui/TextField';

class Messages extends Component {

    constructor(props) {
        super(props)

        this.state = {
            height: 0
        }
    }

    componentDidMount() {
        const height = this.input.clientHeight;
        this.setState({ height: height });
    }

    render() {
        const outputStyle = {
            overflowY:'scroll',
            height:`calc(100%-${this.state.height})`
        };

        const inputStyle = {
            position:'fixed',
            bottom:'0',
            height:'auto'
        };

        return (
            <div style={{height:'100%'}}>
                <div name="output" style={outputStyle}/>
                <TextField name="input" multiLine={true} fullWidth={true} underlineShow={false} style={inputStyle} rows={2} ref={(input) => {this.input = input;}} />
            </div>
        );
    }
}

export default Messages;

My objective is to define the height of the element "output" by this way : 100% - this.state.height.

Upvotes: 0

Views: 1332

Answers (2)

user6620828
user6620828

Reputation:

a ref on a custom component returns the component instance, not a dom node

I have to use: ReactDOM.findDOMNode(this.input).clientHeight;

Upvotes: 1

Nevosis
Nevosis

Reputation: 1415

setState is asynchronous, your state will properly update somehow after the call. Then render will be called again. Try checking your new state in render or in componentWillUpdate : https://facebook.github.io/react/docs/react-component.html#componentwillupdate

You should never look for a change in your state right after changing your state.

Just set your outputStyle.height to this.state.height and you should be good.

Upvotes: 0

Related Questions