Generate keys for arrays of elements to remove React warnings. Pass only a single child if possible.

This commit is contained in:
Andrey Okonetchnikov 2016-09-22 18:23:44 +02:00
parent 7fe1a6f8b6
commit c243a62a32

View File

@ -21,21 +21,26 @@ const defaultRenderers = {
'unstyled': null, 'unstyled': null,
}; };
function renderToken(token) { function renderToken(token, index = 0, key = '0') {
const { type, data, text, tokens } = token; const { type, data, text, tokens } = token;
const element = defaultRenderers[type]; const element = defaultRenderers[type];
key = `${key}.${index}`;
// Only render if type is registered as renderer // Only render if type is registered as renderer
if (typeof element !== 'undefined') { if (typeof element !== 'undefined') {
let children = null; let children = null;
if (Array.isArray(tokens) && tokens.length) { if (Array.isArray(tokens) && tokens.length) {
children = tokens.map(renderToken); children = tokens.map((token, idx) => renderToken(token, idx, key));
} else if (type === 'text') { } else if (type === 'text') {
children = text; children = text;
} }
if (element !== null) { if (element !== null) {
// If this is a react element // If this is a react element
return React.createElement(element, data, children); return React.createElement(
element,
{ key, ...data }, // Add key as a prop
Array.isArray(children) && children.length === 1
? children[0] : children); // Pass single child if possible
} else { } else {
// If this is a text node // If this is a text node
return children; return children;