Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81152 views
1
/**
2
* Copyright 2013-2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*
9
* @providesModule flattenChildren
10
*/
11
12
"use strict";
13
14
var ReactTextComponent = require('ReactTextComponent');
15
16
var traverseAllChildren = require('traverseAllChildren');
17
var warning = require('warning');
18
19
/**
20
* @param {function} traverseContext Context passed through traversal.
21
* @param {?ReactComponent} child React child component.
22
* @param {!string} name String name of key path to child.
23
*/
24
function flattenSingleChildIntoContext(traverseContext, child, name) {
25
// We found a component instance.
26
var result = traverseContext;
27
var keyUnique = !result.hasOwnProperty(name);
28
warning(
29
keyUnique,
30
'flattenChildren(...): Encountered two children with the same key, ' +
31
'`%s`. Child keys must be unique; when two children share a key, only ' +
32
'the first child will be used.',
33
name
34
);
35
if (keyUnique && child != null) {
36
var type = typeof child;
37
var normalizedValue;
38
39
if (type === 'string') {
40
normalizedValue = ReactTextComponent(child);
41
} else if (type === 'number') {
42
normalizedValue = ReactTextComponent('' + child);
43
} else {
44
normalizedValue = child;
45
}
46
47
result[name] = normalizedValue;
48
}
49
}
50
51
/**
52
* Flattens children that are typically specified as `props.children`. Any null
53
* children will not be included in the resulting object.
54
* @return {!object} flattened children keyed by name.
55
*/
56
function flattenChildren(children) {
57
if (children == null) {
58
return children;
59
}
60
var result = {};
61
traverseAllChildren(children, flattenSingleChildIntoContext, result);
62
return result;
63
}
64
65
module.exports = flattenChildren;
66
67