Created
January 23, 2019 06:40
-
-
Save dantman/d6b18a55b6074ad179951c683363fef3 to your computer and use it in GitHub Desktop.
Render prop component that returns a unique id
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 warning from 'warning'; | |
import { Component } from 'react'; | |
let idCounter = 0; | |
function nextId() { | |
idCounter += 1; | |
warning( | |
idCounter < 1e10, | |
'Id: you might have a memory leak.' + | |
'The idCounter is not supposed to grow that much.' | |
); | |
return idCounter; | |
} | |
/** | |
* A simple render prop component that returns a unique id | |
*/ | |
export default class Id extends Component { | |
state = { | |
id: nextId(), | |
}; | |
getId() { | |
const { name } = this.props; | |
const { id } = this.state; | |
if (process.env.NODE_ENV === 'production') { | |
return `uid${id}`; | |
} | |
return `${name || 'unnamed'}-${id}`; | |
} | |
render() { | |
return this.props.children(this.getId()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment