Skip to content

Instantly share code, notes, and snippets.

@gbozee
Last active February 22, 2018 20:06
Show Gist options
  • Save gbozee/d98c138bb866ed14f52e3f5d4e586574 to your computer and use it in GitHub Desktop.
Save gbozee/d98c138bb866ed14f52e3f5d4e586574 to your computer and use it in GitHub Desktop.
Buggy Case
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
class ChildComponent extends React.Component {
componentDidMount() {
this.props.getHeight(this.node.offsetHeight);
}
render() {
return (
<div ref={node => (this.node = node)}>
<h2>I am interested in the height of this component</h2>
<p>This is just a dummy data to get the height of this component.</p>
</div>
);
}
}
class ParentComponent extends React.Component {
nodes = [];
state = {
heights: []
};
getHeight = height => {
let h = [...this.state.heights, height];
this.setState({ heights: h });
};
render() {
return (
<React.Fragment>
{[1, 2, 3, 4].map((item, index) => (
<ChildComponent key={index} getHeight={this.getHeight} />
))}
<p>The heights with the bug are {this.state.heights.join(" ")}</p>
</React.Fragment>
);
}
}
const App = () => (
<div style={styles}>
<Hello name="CodeSandbox" />
<ParentComponent />
</div>
);
render(<App />, document.getElementById("root"));
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
class ChildComponent extends React.Component {
render() {
return (
<div ref={node => (this.node = node)}>
<h2>I am interested in the height of this component</h2>
<p>This is just a dummy data to get the height of this component.</p>
</div>
);
}
}
class ParentComponent extends React.Component {
nodes = [];
state = {
nodeHeights: []
};
componentDidMount() {
let heights = this.nodes.map(x => x.node.offsetHeight);
this.setState({ nodeHeights: heights });
}
render() {
return (
<React.Fragment>
{[1, 2, 3, 4].map((item, index) => (
<ChildComponent
ref={node => this.nodes.push(node)}
key={index}
/>
))}
<p>
The heights without the bug are {this.state.nodeHeights.join(" ")}
</p>
</React.Fragment>
);
}
}
const App = () => (
<div style={styles}>
<Hello name="CodeSandbox" />
<ParentComponent />
</div>
);
render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment