Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort inbound props in a ReactJS component?

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>
    }
}
like image 250
Ben Aston Avatar asked Mar 26 '26 01:03

Ben Aston


1 Answers

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() {...}
}
like image 168
Raicuparta Avatar answered Mar 27 '26 13:03

Raicuparta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!