Skip to content

Instantly share code, notes, and snippets.

@phated
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phated/a23e04a09669d6d95533 to your computer and use it in GitHub Desktop.
Save phated/a23e04a09669d6d95533 to your computer and use it in GitHub Desktop.
Idiomatic React - Rule #1: Don't generate children; Always forward them.
/*
List is an abstract React component for building lists.
Think of it like a wrapper around <ul> or <ol>
*/
var List = require('custom-components/list');
/*
ListItem is an abstract React component for adding items to the List component.
Think of this like a <li> that might have styling, classes, etc to work nicer in the List.
*/
var ListItem = require('custom-components/list-item');
function onClick(item, evt){
evt.stopPropagation();
evt.preventDefault();
console.log('List item #' + item + ' clicked');
}
/*
You will notice that we are able to attach custom handlers, keys, etc to each item because
we generated the children. If we were handing an array of objects off to the List, we
could only do what was allowed by the object's schema definition.
Also, we are allowed to put any elements we want in the List, not just the ListItem component.
This allows consumers to work around limitations in APIs of things like the abstract
ListItem component. They could even inherit from ListItem and add custom behavior or styling.
This would be impossible with an array of objects.
*/
React.render(
<List className="my-list">
<ListItem key="item1" onClick={onClick.bind(null, 1)}>List Item #1</ListItem>
<ListItem key="item2" onClick={onClick.bind(null, 2)}>List Item #2</ListItem>
<ListItem key="item3" onClick={onClick.bind(null, 3)}>List Item #3</ListItem>
<div className="my-div-in-list">Some div that I styled specifically for living in a List</div>
</List>
)
var List = require('custom-components/list');
var listItems = [
{ text: 'item1', itemNumber: 1 },
{ text: 'item2', itemNumber: 2 },
{ text: 'item3', itemNumber: 3 }
];
function onSelected(item, evt){
// hopefully they actually passed you the event, most don't
evt.stopPropagation();
evt.preventDefault();
console.log('List item #' + item + ' clicked');
}
/*
While this implementation of List may be more terse for the end user,
it comes at a very high cost; To do anything outside of the scope defined
by the component author, you are forced to fork the project or in some way
alter the internals of the List component.
You are also reliant on them implementing a sane version of onSelected vs
just using standard onClick + functions (including bind/partial/etc)
*/
React.render(<List className="my-list" items={items} onSelected={onSelected} />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment