Is there anyway of getting the width of React component children. I have wrapper component called for lack of name Container and I add children of div type from Component1 to it. See below example. I'm wondering if there is a way to get the width of each div child in Container when it mounts.
UPDATED NOTE: The reason I'm trying to get the containers children widths is so I can dynamical set the containers width based on the total number of children. By setting the containers width to the number of children's width then I can allow for some horizontal scrolling effects I want to do.
Component 1
export default class Component1 extends Component{
render(){
return(
<Container>
<div className="large-box"/>
<div className="large-box-dark"/>
</Container>
)
}
}
Now my Container component.
export default class Container extends Component{
componentDidMount(){
this.props.children.forEach(( el ) => {
// get each child's width
console.log("el =", el);
});
}
render() {
return (
<div className="scroller" ref={(scroller) => { this.scroller = scroller }}>
{this.props.children}
</div>
)
}
}
You can use refs
. Although you should avoid touching the DOM until and unless there is no other way. But here we go.
Give your child components a ref which is escape hatch provided by React to access the DOM(with a warning to use other methods before coming to this).
Child Component
class ChildComp extends Component {
getWidth = () => {
//Access the node here and get the width
return this.childNode.offsetWidth(); //or clientWidth();
}
render() {
return (
<div ref={(r) => {this.childNode = r}}>
</div>
);
}
}
Parent Component:
class ParentComp extends Component {
componentDidMount() {
//Access the child component function from here
this.childComponent.getWidth();
}
render() {
return (
<ChildComp
ref={(r) => {this.childComponent = r}} />
);
}
}
But do remember use the above method when there is no way of getting the thing done declaratively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With