I have a ponent that looks as follows:
export default class WebGLCanvas extends Component {
render() {
return (
<div class="canvas-container">
<Renderer></Renderer>
</div>
)
}
}
However, in order to instance the <Renderer>
ponent, I need to provide it a width and a height property, which will only be defined after the .canvas-container
is instanced.
What is the appropriate way to pass DOM element properties to child ponents?
I have a ponent that looks as follows:
export default class WebGLCanvas extends Component {
render() {
return (
<div class="canvas-container">
<Renderer></Renderer>
</div>
)
}
}
However, in order to instance the <Renderer>
ponent, I need to provide it a width and a height property, which will only be defined after the .canvas-container
is instanced.
What is the appropriate way to pass DOM element properties to child ponents?
Share Improve this question asked Jun 13, 2016 at 17:32 corvidcorvid 11.2k12 gold badges71 silver badges135 bronze badges2 Answers
Reset to default 5I guess you are trying to implement a Renderer
which will need height and width to calculate the dimensions for its child events:
constructor() {
super();
this.state = {height: 0, width: 0};
}
ponentDidMount() {
window.addEventListener('resize', this.resetDimensions);
this.resetDimensions();
}
ponentWillUnmount() {
window.removeEventListener('resize', this.resetDimensions);
}
resetDimensions() {
var canvasContainer = this.refs.canvasContainer;
this.setState({width: canvasContainer.clientWidth, height: canvasContainer.clientHeight});
}
The above code basically, sets a height
and width
as state to your WebGLCanvas ponent.
Using this you can pass the height and width to the Renderer ponent as props, like:
return (
<div className="canvas-container" ref="canvasContainer">
<Renderer height={this.state.height} width={this.state.width}></Renderer>
</div>
)
I hope this helps.
P.S. The call to getDOMNode
may or may not be required, depending on the React version.
I think you need to make the canvas-container
its own ponent that passes the needed properties to its children ponent <Renderer/>
. Something like:
Given code:
export default class WebGLCanvas extends Component {
render() {
return <CanvasContainer />; // use the canvas-container ponent
}
}
Canvas container:
export default class CanvasContainer extends Component {
constructor(props) {
super(props);
// initialize the state
this.state = {
width: 0,
height: 0
};
}
render() {
const { width, height } = this.state;
return <Renderer width={width} height={height}></Renderer>
}
}
And wherever you set width
and height
in CanvasContainer
, you set them through the state:
this.setState({ width, height });
which will re-render the Renderer
ponent and pass these into its props