Last active
August 24, 2016 13:33
-
-
Save octopitus/38344022fa58ca945cded9a5cc08168c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Asume that your card has ID | |
const card = { | |
id: 'foo', | |
category: 'bar' | |
// ... | |
} | |
// This is how your app state looks like | |
const appState = { | |
entities: { | |
cards: { | |
// Data received from server | |
} | |
}, | |
result: [ | |
// And after transformed by normalizr | |
], | |
// An object hold all opened cards | |
isOpenedCards: { | |
abcxyz: true // Key is ID of card | |
}, | |
filterBy: { | |
category: 'bar' | |
} | |
} | |
// Your reducer | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'RECEIVED_DATA_FROM_SERVER': { | |
return { | |
...state, | |
result: actions.result, | |
entities: { | |
cards: action.cards | |
} | |
} | |
} | |
case 'FILTER_CARDS_BY_CATEGORY': { | |
return { | |
...state, | |
filterBy: { | |
category: action.categoryName | |
} | |
} | |
} | |
case 'TOGGLE_OPEN_CARD': { | |
const { isOpenedCards } = state | |
const { cardId } = action | |
return { | |
...state, | |
isOpenedCards: { | |
...isOpenedCards, | |
{[cardId]: !isOpenedCards[cardId] | |
} | |
} | |
} | |
} | |
} | |
// Card item | |
class CardItem extends React.Component { | |
shouldComponentUpdate(nextProps) { | |
return ( | |
nextProps.data !== this.props.data || | |
nextProps.isOpen !== this.props.isOpen | |
) | |
} | |
render() { | |
return ( | |
<div> | |
// Markups for each card | |
</div> | |
) | |
} | |
} | |
// Your container component | |
class CardContainer extends React.Component { | |
shouldComponentUpdate(nextProps) { | |
return ( | |
nextProps.result !== this.props.result || | |
nextProps.entities !== this.props.entities || | |
nextProps.filterBy !== this.props.filterBy || | |
nextProps.isOpenedCards !== this.props.isOpenedCards | |
) | |
} | |
render() { | |
const isOpendCards = this.props.isOpenedCards | |
const {category} = this.props.filterBy | |
const {cards} = this.props.entities | |
const filteredCards = this.props.result.filter( | |
id => cards[id].category === category | |
) | |
return ( | |
<div> | |
{filteredCards.map(id => <CardItem data={cards[id]} isOpen={isOpenedCards[id]} />)} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment