Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created October 4, 2016 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwietelmann/c1bde95040a13a28c9da4099bc9462b9 to your computer and use it in GitHub Desktop.
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.
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