Ben Aston
Ben Aston

Reputation: 55729

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>
    }
}

Upvotes: 3

Views: 2694

Answers (1)

Raicuparta
Raicuparta

Reputation: 2115

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() {...}
}

Upvotes: 2

Related Questions