Reputation: 551
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
Reputation: 1582
There are two problems I see with the code.
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
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