UNPKG

1.24 kBJavaScriptView Raw
1import * as React from 'react';
2import { counter, getId, getPrefix } from './context';
3// --------------------------------------------
4const prefixId = (id, prefix, name) => {
5 const uid = prefix + id;
6 return String(name ? name(uid) : uid);
7};
8/**
9 * @deprecated
10 * UID in form of renderProps (not SSR friendly)
11 * @see https://github.com/thearnica/react-uid#react-components
12 * @example
13 * // get UID to connect label to input
14 * <UID>
15 * {(id)} => <label htmlFor={id}><input id={id}/>}
16 * </UID>
17 *
18 * // get uid to generate uid for a keys in a list
19 * <UID>
20 * {(, uid)} => items.map(item => <li key={uid(item) />)}
21 * </UID>
22 */
23export class UID extends React.Component {
24 constructor() {
25 super(...arguments);
26 this.state = {
27 quartz: this.props.idSource || counter,
28 prefix: getPrefix(this.props.idSource),
29 id: getId(this.props.idSource || counter),
30 };
31 this.uid = (item) => prefixId(this.state.id + '-' + this.state.quartz.uid(item), this.state.prefix, this.props.name);
32 }
33 render() {
34 const { children, name } = this.props;
35 const { id, prefix } = this.state;
36 return children(prefixId(id, prefix, name), this.uid);
37 }
38}