Reputation: 1368
I have a container element, which is also a React component, with a specific height. I also have an API that returns blocks of contents of variable length, based on the requested ID.
<Contents/>
I want to request a new block of content from the API until the container is overflowing.
My code works, but it rerenders all content blocks and adds one in each render, until the container is full. This seems like a bad approach.
class Contents extends React.Component {
constructor() {
super();
this.state = {
numElements: 0
};
}
render() {
const elements = [];
for(let i = 0; i < this.state.numElements; i++) {
elements.push(this._getElementContents(i));
}
return(<div id="contents">
{elements.map(element => element)}
</div>);
}
componentDidMount() {
// start the 'filling loop'
this._addElement();
}
componentDidUpdate() {
// keep adding stuff until container is full
if(document.getElementById('contents').clientHeight < window.outerHeight - 400) {
this._addElement();
}
}
_addElement() {
// setState will cause render() to be called again
this.setState({numElements: this.state.numElements + 1});
}
_getElementContents(i) {
// simplified, gets stuff from API:
let contents = api_response;
return(<Element key={i} body={contents} />);
}
}
How can I append elements to the container until it is filled, without re-adding, re-querying the API and re-rendering existing elements on each loop?
Upvotes: 0
Views: 1001
Reputation: 1327
Because this.setState() triggers a re-render, like dimitrisk said, you should put logic in shouldComponentUpdate to only render once you have everything ready to go to the DOM.
You should look into Dynamic Children in React. It helps React do reconciliation when re-rendering http://facebook.github.io/react/docs/multiple-components.html#dynamic-children http://revelry.co/dynamic-child-components-with-react/
Upvotes: 1
Reputation: 774
I can't see how you are calling your API or under what condition. From my understanding you should do two things.
Keep elements
array into the state
object and push new elements whenever they arrive.
Use the shouldComponentUpdate
instead of componentDidUpdate
with the same exactly condition to judge when you have to request more elements from your API.
Eventually draw the state.elements
. Whenever you receive a new one you just use the local elements you previously got to redraw the component instead of making all API calls all over again
Upvotes: 3