UNPKG

2.01 kBJavaScriptView Raw
1import * as React from 'react';
2import { useState } from 'react';
3import { UID } from './UIDComponent';
4import { createSource, source } from './context';
5import { useUID } from './hooks';
6/**
7 * UID isolation component, required for SSR and testing.
8 * Wrap your application with it to guarantee UID consistency between SSR and CSR.
9 * @param {String} [prefix] - prefix for all generated ids
10 * @example
11 * <UIDReset>
12 * <App />
13 * </UIDReset/>
14 * @see https://github.com/thearnica/react-uid#server-side-friendly-uid
15 */
16export const UIDReset = ({ children, prefix = '' }) => {
17 const [valueSource] = useState(() => createSource(prefix));
18 return React.createElement(source.Provider, { value: valueSource }, children);
19};
20/**
21 * Creates a sub-ids for nested components, isolating from inside a branch.
22 * Useful for self-contained elements or code splitting
23 * @see https://github.com/thearnica/react-uid#code-splitting
24 */
25export const UIDFork = ({ children, prefix = '' }) => {
26 const id = useUID();
27 const [valueSource] = useState(() => createSource(id + '-' + prefix));
28 return React.createElement(source.Provider, { value: valueSource }, children);
29};
30/**
31 * UID in form of renderProps. Supports nesting and SSR. Prefer {@link useUID} hook version if possible.
32 * @see https://github.com/thearnica/react-uid#server-side-friendly-uid
33 * @see https://github.com/thearnica/react-uid#react-components
34 * @example
35 * // get UID to connect label to input
36 * <UIDConsumer>
37 * {(id)} => <label htmlFor={id}><input id={id}/>}
38 * </UIDConsumer>
39 *
40 * // get uid to generate uid for a keys in a list
41 * <UIDConsumer>
42 * {(, uid)} => items.map(item => <li key={uid(item) />)}
43 * </UIDConsumer>
44 *
45 * @see {@link useUID} - a hook version of this component
46 * @see {@link UID} - not SSR compatible version
47 */
48export const UIDConsumer = ({ name, children }) => (React.createElement(source.Consumer, null, (value) => React.createElement(UID, { name: name, idSource: value, children: children })));