How to sort list – react-redux example

We have created a React Application that connects with Redux, then filter list of items with input text. In this tutorial, we continue to sort that list using react-redux.

Example Overview

We can sort list of items by ‘title’ or ‘published’:

react-redux-example-sort-list-goal

Sort list

Context

Remember that our App state is like this:

const demoState = {
    books: [
        {
            id: '123abcdefghiklmn',
            title: 'Origin',
            description: 'Origin thrusts Robert Langdon into the dangerous intersection of humankind’s two most enduring questions.',
            author: 'Dan Brown',
            published: 2017
        }
    ],
    filters: {
        text: 'ori',
        sortBy: 'published', // published or title
        startYear: undefined,
        endYear: undefined
    }
};

And our Book list is displayed based on getVisibleBooks() function:

// BookList.js
const BookList = (props) => (
    // display 'books'
);

const mapStateToProps = (state) => {
    return {
        books: getVisibleBooks(state.books, state.filters)
    };
}

export default connect(mapStateToProps)(BookList);

getVisibleBooks(books, filters) returns Book list by filtering and sorting input books.

// getVisibleBooks
export default (books, { text, sortBy, startYear, endYear }) => {
    return books.filter(book => {
        // ...
        return textMatch && startYearMatch && endYearMatch;
    }).sort((book1, book2) => {
        if (sortBy === 'title') {
            // ...
        } else if (sortBy === 'published') {
            // ...
        }
    });
}

=> Updating filters state will change the list of displayed item (books).

Solution

In this example, we only update filters.sortBy. To do this, we need:
– options for choosing ‘title’ or ‘published’ => BookFilters Component has html select with 2 option inside.
– to connect BookFilters Component with Redux store to get access to filters state => import react-redux connect() and use mapStateToProps.
– to handle button click event => add onChange and use Redux dispatch() with sortBy Action imported from actions/filters.

Practice

Add select to template

Inside components/BookFilters.js:

import React from 'react';
import { connect } from 'react-redux';
import { ..., sortBy } from '../actions/filters';

class BookFilters extends React.Component {
    // ...

    render() {
        return (
            
sorted By:
); } } const mapStateToProps = (state) => { return { filters: state.filters } } export default connect(mapStateToProps)(BookFilters);
Run and Check Result
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import AppRouter from './routers/AppRouter';
import getAppStore from './store/store';
import { addBook } from './actions/books';
import { filterText, startYear, endYear, sortBy, clear } from './actions/filters';
import getVisibleBooks from './selectors/books';
import './styles/styles.scss';

import { Provider } from 'react-redux';

const store = getAppStore();

store.dispatch(addBook({
    title: 'Origin',
    description: 'Origin thrusts Robert Langdon into the dangerous intersection of humankind’s two most enduring questions.',
    author: 'Dan Brown',
    published: 2017
}));

store.dispatch(addBook({
    title: 'Harry Potter and the Goblet of Fire',
    description: 'A young wizard finds himself competing in a hazardous tournament between rival schools of magic, but he is distracted by recurring nightmares.',
    author: 'J. K. Rowling',
    published: 2000
}));

store.dispatch(addBook({
    title: 'Harry Potter and the Deathly Hallows',
    description: 'The seventh and final novel of the Harry Potter series.',
    author: 'J. K. Rowling',
    published: 2007
}));

store.dispatch(addBook({
    title: 'The 100-Year-Old Man Who Climbed Out the Window and Disappeared',
    author: 'Jonas Jonasson',
    published: 2009
}));

const template = (
    
        
    
);

ReactDOM.render(template, document.getElementById('app'));
Check Result

– sortBy Title:

– sortBy Published:

react-redux-example-sort-list-result-published

Source Code

ReactRedux-sort

For running:
yarn install
yarn run dev-server or yarn run build, then yarn run serve.



By grokonez | April 18, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*