I have a ReactJS component that has a prop that is a collection.
I want to ensure this collection is always sorted for the component.
Where should I place the sorting logic?
Putting it inside the JSX will mean it is run on every render, which is inefficient.
class MyComponent {
render() {
const { collection } = this.props; // I want collection to stay sorted
return <div>collection.map(i => <div>i</div>)</div>
}
}
If for some reason you can't sort it before sending it to the component, componentWillReceiveProps would be good for this:
class MyComponent {
this.sorted = [];
componentWillReceiveProps(nextProps) {
// Here you can check if the collection has changed
// and skip the sort if it hasn't.
this.sorted = sort(nextProps.collection);
}
render() {...}
}
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