Created
February 21, 2017 10:29
-
-
Save schabluk/62fe7415ad8f86b3328106fcad713576 to your computer and use it in GitHub Desktop.
Stateless Component
This file contains 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
import React, { PropTypes } from 'react' | |
/** | |
* Moving click handler function outside of the component | |
* follows the separation of concerns principle (SoC). | |
*/ | |
const _handleClick = (onSelect, event, id) => { | |
// Additional steps before handling action. | |
event.preventDefault() | |
event.stopPropagation() | |
// Call function passed from the parent component. | |
onSelect(id) | |
} | |
/** | |
* - The component is Pure; has no state and returns the same markup | |
* given the same props. That makes it easy to test and maintain. | |
* For brevity, it is defined as a function, rather than a class. | |
* | |
* - There should be no 'contextType' nor 'defaultProps', | |
* as they can mutate function state. The default props | |
* can be passed as default function arguments. | |
* | |
* - Props are clearly definded using Destructuring assignment, | |
* and additional props are passed using Spread syntax. | |
*/ | |
const Item = ({id, title = 'Default value', onSelect, children, ...props}) => { | |
return <div onClick={e => _handleClick(onSelect, e, id)} {...props}> | |
{/* The component has a set of common properties, like 'title'. */} | |
<div>{title}</div> | |
{/* Custom components can be injected as children. */} | |
{children} | |
</div> | |
} | |
// The propTypes property defines component's interface. | |
Item.propTypes = { | |
id: PropTypes.string, | |
title: PropTypes.string, | |
onSelect: PropTypes.func, | |
children: PropTypes.node | |
} | |
// The displayName property value is set for better debugging messages. | |
Item.displayName = 'Item' | |
export default Item |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment