Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/** This Component can be used to wrap a functional component in order to generate a random ID
* Example of how to use this component
*
* const Component = ({id}) => (
* <GenerateId>{randomId => (
* <div id={id || randomId}>
* div with random ID
* </div>
* )}
* </GenerateId>
* );
*
* Component.propTypes = {
* id: PropTypes.string
* }
*/

import React from 'react';
import PropTypes from 'prop-types';

let currentId = 0;

const propTypes = {
/** String to prefix the random id with */
prefix: PropTypes.string,
/** Component to be rendered with the generated id */
children: PropTypes.func.isRequired
};

class GenerateId extends React.Component {
static defaultProps = {
prefix: 'pf-random-id-'
};
static propTypes = propTypes;
id = `${this.props.prefix}${currentId++}`;

render() {
return this.props.children(this.id);
}
}

export default GenerateId;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react';
import { shallow } from 'enzyme';
import GenerateId from './GenerateId';

test('generates id', () => {
const view = shallow(<GenerateId>{id => <div id={id}>div with random ID</div>}</GenerateId>);

expect(view).toMatchSnapshot();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`generates id 1`] = `
<div
id="pf-random-id-0"
>
div with random ID
</div>
`;