Skip to content

Instantly share code, notes, and snippets.

@dantman
Created January 23, 2019 06:40
Show Gist options
  • Save dantman/d6b18a55b6074ad179951c683363fef3 to your computer and use it in GitHub Desktop.
Save dantman/d6b18a55b6074ad179951c683363fef3 to your computer and use it in GitHub Desktop.
Render prop component that returns a unique id
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