Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

reactjs

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

like image 336
user2991413 Avatar asked Aug 31 '26 23:08

user2991413


2 Answers

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';
like image 159
Rannie Aguilar Peralta Avatar answered Sep 03 '26 17:09

Rannie Aguilar Peralta


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

like image 22
Saurabh Nemade Avatar answered Sep 03 '26 18:09

Saurabh Nemade