Created
October 4, 2016 16:20
-
-
Save jwietelmann/c1bde95040a13a28c9da4099bc9462b9 to your computer and use it in GitHub Desktop.
React unique ID via context. Every render of the Provider resets the counter.
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, {Component, PropTypes, Children, createElement} from 'react' | |
const CONTEXT_NAME = '__uniqueIDFunction__' | |
const CONTEXT_TYPES = {} | |
CONTEXT_TYPES[CONTEXT_NAME] = PropTypes.func | |
function createUniqueIDFunction() { | |
let counter = 0 | |
return function() { | |
return ++counter | |
} | |
} | |
class UniqueIDFunctionProvider extends Component { | |
static childContextTypes = CONTEXT_TYPES; | |
getChildContext() { | |
const context = {} | |
context[CONTEXT_NAME] = createUniqueIDFunction() | |
return context | |
} | |
render() { | |
return <div>{this.props.children}</div> | |
} | |
} | |
export const Provider = UniqueIDFunctionProvider; | |
class UniqueIDFunctionReceiver extends Component { | |
static contextTypes = CONTEXT_TYPES; | |
getChildProps() { | |
const idProps = this.constructor.uniqueIDToProps(this.context[CONTEXT_NAME]) | |
return {...idProps, ...this.props} | |
} | |
render() { | |
return createElement(this.constructor.componentClass, this.getChildProps()) | |
} | |
} | |
export function connect(uniqueIDToProps) { | |
return function(componentClass) { | |
return class extends UniqueIDFunctionReceiver { | |
static componentClass = componentClass; | |
static uniqueIDToProps = uniqueIDToProps; | |
} | |
} | |
} | |
// EXAMPLE | |
// const Item = ({id}) => <div id={id}>My ID is <strong>{id}</strong></div> | |
// const ConnectedItem = connect( | |
// (getUniqueId) => ({id: `item-${getUniqueId()}`}) | |
// )(Item) | |
// | |
// export class Example extends Component { | |
// render() { | |
// return ( | |
// <Provider> | |
// <ConnectedItem /> | |
// <ConnectedItem /> | |
// </Provider> | |
// ) | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment