user2991413
user2991413

Reputation: 551

React: How to set width and height of an element in react component programatically

I want to set a container's width and height programmatically based on some calculation.

I am trying to set style of the ref i created for the element in componentDidUpdate() but it has no effect

export default class CanvasOverlay extends React.Component {
    static propTypes = {
        imageURI : PropTypes.string.isRequired,
    };

    constructor(props) {
        super(props);
        this.width = 0;
        this.height = 0;
        this.canvasOverlay = React.createRef();
    }

    componentDidMount() {
        let image = new Image();
        let that = this;
        image.onload = function() {
            that._updateDimension(image.width, image.height);
        };
        image.src = this.props.imageURI;
    }

    _updateDimension(imageWidth, imageHeight) {
        const canvasOverlay = this.canvasOverlay.current;
        //Ideally there should be some calculations to get width and 
         height
        canvasOverlay.style.width = 480;
        canvasOverlay.style.height = 400;
    }

    render() {
        return(
            <div ref={this.canvasOverlay}>
                <Canvas imageURI={this.props.imageURI}/>
            </div>
        );
    }
}

HTML element canvasOverlay should have resized but it has not

Upvotes: 3

Views: 27294

Answers (2)

Saurabh Nemade
Saurabh Nemade

Reputation: 1582

There are two problems I see with the code.

  • _updateDimension is invoked from componentDidMount. ComponentDidMount gets called only once in lifecycle of component, which means it will always take initial size to compute width and height. Resize of the browser will not reflect correct width and you might see overflow.
  • canvasOverlay.style.width & canvasOverlay.style.height will require string instead of number. for e.g. "400px"

Here is a good explanation about the lifecycle of React Component: https://medium.com/@nancydo7/understanding-react-16-4-component-lifecycle-methods-e376710e5157

Here is a working POC with the given code: https://stackblitz.com/edit/react-hosymf?file=CanvasOverlay.js

Upvotes: 2

Rannie Aguilar Peralta
Rannie Aguilar Peralta

Reputation: 1742

The style.width and style.height of element doesn't accept a value with a type number so you should convert it to a string and add a 'px' unit.

element.style.width = `${width}px`;

// or

element.style.width = width + 'px';

Upvotes: 7

Related Questions