react#Children JavaScript Examples
The following examples show how to use
react#Children.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: children-utilities.js From react-dsfr with MIT License | 7 votes |
deepForEach = (children, deepForEachFn) => {
Children.forEach(children, (child, index) => {
if (isValidElement(child) && hasComplexChildren(child)) {
// Each inside the child that has children
deepForEach(child.props.children, deepForEachFn);
}
deepForEachFn(child, index);
});
}
Example #2
Source File: util.js From spring-boot-ecommerce with Apache License 2.0 | 7 votes |
export function traverseTreeNodes(treeNodes, callback) {
function processNode(node, index, parent) {
var children = node ? node.props.children : treeNodes;
var pos = node ? getPosition(parent.pos, index) : 0; // Filter children
var childList = getNodeChildren(children); // Process node if is not root
if (node) {
var data = {
node: node,
index: index,
pos: pos,
key: node.key || pos,
parentPos: parent.node ? parent.pos : null
};
callback(data);
} // Process children node
Children.forEach(childList, function (subNode, subIndex) {
processNode(subNode, subIndex, {
node: node,
pos: pos
});
});
}
processNode(null);
}
Example #3
Source File: ToggleButtonGroup.jsx From ui-neumorphism with MIT License | 6 votes |
render() {
const { style, children, multiple, className } = this.props
const buttons = passDownProp(
Children.map(children, (child) => {
if (child.type === ToggleButton) {
let selected = false
const { active } = this.state
const { value } = child.props
if (Array.isArray(active)) {
const trimmedActive = multiple
? active
: active.filter((a, i) => i === 0)
selected = !!trimmedActive.find((a) => a === value)
} else {
selected = active === value
}
return cloneElement(child, {
selected,
key: this.state.key,
onChange: (e) => this.handleClick(e, child)
})
}
}),
this.props,
['size', 'color', ...CARD_PASS_DOWN]
)
return (
<div style={style} className={className}>
{buttons}
</div>
)
}
Example #4
Source File: ButtonGroup.js From beautiful-react-ui with MIT License | 6 votes |
ButtonGroup = ({ children, className, fluid, id, style, ...props }) => {
// the reason I'm disabling eslint "react/destructuring-assignment" rule is that I want to keep some props within the
// props constant, as it will then be passed as a parameter to the cloneButton function.
/* eslint-disable react/destructuring-assignment */
const classList = classNames('bi bi-btn-group', `btn-group-${props.color}`, {
'group-fluid': fluid,
'group-outline': props.outline,
'group-rounded': props.rounded,
}, className);
/* eslint-enable react/destructuring-assignment */
return (
<span className={classList} id={id} style={style}>
{Children.map(children, (child) => cloneButton(child, props))}
</span>
);
}
Example #5
Source File: tab.js From React-Messenger-App with MIT License | 6 votes |
Tab = React.memo((props) => {
const { children, active, onChange, color, orientation, className, ...rest } = props;
const tabContents = Children.toArray(children).map((child, index) => filterTabChildren(child, index, props));
const classList = classNames(`bi bi-tab tab-color-${color}`, {
'tab-orientation': orientation === 'vertical',
}, className);
return (
<div className={classList} {...rest}>
<nav className="bi-tab-nav">
<ul>
{tabContents.map(({ title, icon, disabled }, index) => (
<TabButton
key={title}
title={title}
icon={icon}
active={active}
index={index}
onChange={onChange}
disabled={disabled}
/>
))}
</ul>
</nav>
<section className="bi-tab-contents">
{tabContents.map(({ child }) => child)}
</section>
</div>
);
})
Example #6
Source File: SettingAccordion.js From Website with MIT License | 6 votes |
SettingAccordion = props => {
const [openItem, setOpenItem] = useState();
const clickHandler = useCallback(key => {
setOpenItem(prev => {
if (key === prev) {
return "";
} else {
return key;
}
});
}, []);
return (
<div style={{ width: "100%" }}>
{Children.map(props.children, Element =>
cloneElement(Element, {
onClick: clickHandler,
open: Element.props?.name === openItem,
})
)}
</div>
);
}
Example #7
Source File: index.js From flame-coach-web with MIT License | 6 votes |
TouchCellWrapper = ({
children,
value,
onSelectSlot
}) =>
React.cloneElement(Children.only(children), {
onTouchEnd: () => onSelectSlot({
action: 'click',
slots: [value]
}),
style: {
className: `${children}`
}
})
Example #8
Source File: CardGrid.js From HackShack-Session-Landing-Page with MIT License | 6 votes |
CardGrid = ({ children, size, ...rest }) => {
const childrenWithProps = Children.map(children, child => {
if (isValidElement(child)) {
return cloneElement(child, { size });
}
return child;
});
return (
<StyledGrid gap="large" {...rest}>
{childrenWithProps}
</StyledGrid>
);
}
Example #9
Source File: Link.js From mVoterWeb with GNU General Public License v3.0 | 6 votes |
ActiveLink = ({ router, children, ...props }) => {
const child = Children.only(children);
let className = child.props.className || null;
if (router.pathname === props.href && props.activeClassName) {
className = `${className !== null ? className : ''} ${
props.activeClassName
}`.trim();
}
// eslint-disable-next-line no-param-reassign
delete props.activeClassName;
return <Link {...props}>{React.cloneElement(child, { className })}</Link>;
}
Example #10
Source File: recursiveMethods.js From ra-compact-ui with MIT License | 6 votes |
recursivelyFindRealChildren = ({ child, ...props }) => {
// Extract props for local usage but remain in props to get passed forward
const { conditionFnc, renderFnc } = props;
if (conditionFnc(child)) {
// Clone current layout element and continue traversing children
return cloneElement(child, {
children:
Children.count(child.props.children) > 1
? Children.map(
child.props.children,
(innerChild) => recursivelyFindRealChildren({
child: innerChild,
...props,
}),
)
: recursivelyFindRealChildren({
child: child.props.children,
...props,
}),
});
}
// Non-layout element found - recursion's bottom
return renderFnc(child);
}
Example #11
Source File: Keyboard.js From VTour with MIT License | 6 votes |
Keyboard = function Keyboard(_ref) {
var target = _ref.target,
children = _ref.children,
onKeyDown = _ref.onKeyDown,
restProps = _objectWithoutPropertiesLoose(_ref, ["target", "children", "onKeyDown"]);
var onKeyDownHandler = useCallback(function (event) {
var key = event.keyCode ? event.keyCode : event.which;
var callbackName = KEYS[key];
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
if (callbackName && restProps[callbackName]) {
restProps[callbackName].apply(restProps, [event].concat(rest));
}
if (onKeyDown) {
onKeyDown.apply(void 0, [event].concat(rest));
}
}, [onKeyDown, restProps]);
useEffect(function () {
if (target === 'document') {
document.addEventListener('keydown', onKeyDownHandler);
}
return function () {
if (target === 'document') {
document.removeEventListener('keydown', onKeyDownHandler);
}
};
}, [onKeyDownHandler, target]);
return target === 'document' ? children : cloneElement(Children.only(children), {
onKeyDown: onKeyDownHandler
});
}
Example #12
Source File: childrenDeepMap.js From Lambda with MIT License | 6 votes |
export function deepMap(children, callback) {
return Children.map(children, (child) => {
// null happens when conditionally rendering TabPanel/Tab
// see https://github.com/reactjs/react-tabs/issues/37
if (child === null) return null;
if (isTabChild(child)) {
return callback(child);
}
if (
child.props &&
child.props.children &&
typeof child.props.children === 'object'
) {
// Clone the child that has children and map them too
return cloneElement(child, {
...child.props,
children: deepMap(child.props.children, callback),
});
}
return child;
});
}
Example #13
Source File: DockMonitor.js From Learning-Redux with MIT License | 6 votes |
render() {
const { monitorState, children, fluid, ...rest } = this.props;
const { position, isVisible, size } = monitorState;
return (
<Dock position={position}
isVisible={isVisible}
size={size}
fluid={fluid}
onSizeChange={this.handleSizeChange}
dimMode='none'>
{Children.map(children, (child, index) =>
this.renderChild(child, index, rest)
)}
</Dock>
);
}
Example #14
Source File: BadgeGroup.js From react-dsfr with MIT License | 6 votes |
BadgeGroup = ({ children, className, ...remainingProps }) => { const content = Children.toArray(children) // eslint-disable-next-line react/no-array-index-key .map((child, index) => <li key={index}>{child}</li>); const _className = classNames('fr-badges-group', {}, className); return ( <ul className={_className} {...dataAttributes.getAll(remainingProps)} > {content} </ul> ); }
Example #15
Source File: CompositeValidation.js From wix-style-react with MIT License | 6 votes |
children = (...rules) => {
return (props, propName, componentName) => {
if (!rules || rules.length === 0) {
return new Error(
`${componentName} should have at least a single child declaration rule`,
);
}
const childrenAsArray = Children.toArray(props[propName]);
const result = rules.reduce((acc, curr) => {
if (acc === false) {
return acc;
}
return validators[curr.validation](childrenAsArray, acc, curr.type);
}, 0);
if (result === false || childrenAsArray[result]) {
return error(componentName, rules);
}
};
}
Example #16
Source File: index.js From awsboilerplate with MIT License | 6 votes |
function Button(props) {
// Render an anchor tag
let button = (
<A href={props.href} onClick={props.onClick}>
{Children.toArray(props.children)}
</A>
);
// If the Button has a handleRoute prop, we want to render a button
if (props.handleRoute) {
button = (
<StyledButton onClick={props.handleRoute}>
{Children.toArray(props.children)}
</StyledButton>
);
}
return <Wrapper>{button}</Wrapper>;
}
Example #17
Source File: Select.js From dm2 with Apache License 2.0 | 6 votes |
findSelectedChild = (children, value) => {
return Children.toArray(children).reduce((res, child) => {
if (res !== null) return res;
if (child.type.displayName === "Select.Option") {
if (child.props.value === value) {
res = child;
} else if (Array.isArray(value) && value.length === 1) {
res = findSelectedChild(children, value[0]);
}
} else if (child.type.displayName === "Select.OptGroup") {
res = findSelectedChild(child.props.children, value);
}
return res;
}, null);
}
Example #18
Source File: Oneof.js From label-studio-frontend with Apache License 2.0 | 6 votes |
Oneof = ({ value, children, className }) => {
const childList = Children.toArray(children);
const selectedChild = useMemo(() => {
return childList.find(c => c.props.case === value) || null;
}, [childList, value]);
return selectedChild
? cloneElement(selectedChild, {
...selectedChild.props,
className: [className, selectedChild.props.className].join(" "),
})
: null;
}
Example #19
Source File: ActiveLink.js From notes-site with Creative Commons Attribution 4.0 International | 6 votes |
ActiveLink = ({ children, activeClassName, ...props }) => {
const { asPath } = useRouter();
const child = Children.only(children);
const childClassName = child.props.className || "";
// pages/index.js will be matched via props.href
// pages/about.js will be matched via props.href
// pages/[slug].js will be matched via props.as
const className =
asPath === props.href || asPath === props.as
? `${childClassName} ${activeClassName}`.trim()
: childClassName;
return (
<Link {...props}>
{React.cloneElement(child, {
className: className || null,
})}
</Link>
);
}
Example #20
Source File: Accordion.js From lundium with MIT License | 6 votes |
Accordion = forwardRef(({ openItemIndex, className, children }, ref) => {
const [indexOpen, setIndexOpen] = useState(openItemIndex);
useEffect(() => {
if (!isNaN(openItemIndex)) {
setIndexOpen(openItemIndex);
}
}, [openItemIndex]);
useImperativeHandle(ref, () => ({ setActiveIndex: setIndexOpen }));
return (
<Box className={cx('accordion', className)}>
{Children.map(children, (child, index) =>
cond([
[
o(equals(AccordionItem), prop('type')),
clone({ index, indexOpen, setIndexOpen }),
],
[T, identity],
])(child),
)}
</Box>
);
})
Example #21
Source File: ChildMapping.js From mern_docker_demo with MIT License | 6 votes |
/**
* Given `this.props.children`, return an object mapping key to child.
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
export function getChildMapping(children, mapFn) {
var mapper = function mapper(child) {
return mapFn && isValidElement(child) ? mapFn(child) : child;
};
var result = Object.create(null);
if (children) Children.map(children, function (c) {
return c;
}).forEach(function (child) {
// run the map function here instead so that the key is the computed one
result[child.key] = mapper(child);
});
return result;
}
Example #22
Source File: index.js From rainbow-modules with MIT License | 6 votes |
getSearchResults = ({ children, results }) => {
return Children.toArray(children).reduce((seed, child, index) => {
// eslint-disable-next-line no-param-reassign
seed[child.props.name] = {
...results[index],
icon: child.props.icon,
component: child.props.component,
};
return seed;
}, {});
}
Example #23
Source File: ActiveLink.jsx From botble-graphql-next with MIT License | 6 votes |
ActiveLink = ({children, activeClassName, exact, ...props}) => {
const {pathname, asPath} = useRouter();
const child = Children.only(children);
const childClassName = child.props.className || '';
const className = do {
const className = clsx(childClassName, activeClassName);
if (exact && props.as) {
if (contains(props.as, asPath.replace(/[\?#].*/, ''))) {
return className;
}
return childClassName;
}
return pathname === props.href ? className : childClassName;
};
return (
<Link {...props}>
{React.cloneElement(child, {
className: className || null,
})}
</Link>
);
}
Example #24
Source File: InputRow.js From springboot-reactjs-fullstack with MIT License | 6 votes |
InputRow = ({ children, label }) => {
const singleChild = Children.only(children);
const hasInputElement = Children.map(children, child => {
if (child.type === 'input')
return true;
return false;
});
return (
<div style={container}>
<p style={labelStyle}>{label}</p>
<div className="styledInput" >
{
hasInputElement[0] ? singleChild : new Error('an input element is required!')
}
</div>
</div>
);
}
Example #25
Source File: link.jsx From product-collector with MIT License | 6 votes |
Link = ({ router, children, ...props }) => {
const child = Children.only(children);
const activeClassName = props.activeClassName || "active";
let className = child.props.className || "";
if (router.pathname === props.href && activeClassName) {
className = `${className}${activeClassName}`.trim();
}
delete props.activeClassName;
return <NextLink {...props}>{React.cloneElement(child, { className })}</NextLink>;
}
Example #26
Source File: index.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 6 votes |
export function IconStateCatcher (props) {
const [hovered, setHovered] = useState(false)
const [activated, setActivated] = useState(false)
const newChildren = Children.map(
props.children,
(comp) => {
return childWalker(
comp,
(comp) => comp.type && comp.type.icon,
(comp) => cloneElement(comp, { hovered, activated })
)
}
)
return <StateCatcherContainer
className={props.className || ''}
style={props.style || {}}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onMouseDown={() => setActivated(true)}
onMouseUp={() => setActivated(false)}
>
{newChildren}
</StateCatcherContainer>
}
Example #27
Source File: index.js From discovery-mobile-ui with MIT License | 6 votes |
FilterDrawer = ({
children,
}) => {
const drawerRef = useRef(null);
const handleOpenDrawer = () => {
drawerRef.current.openDrawer();
};
const childrenWithProps = Children.map(children, (child) => {
if (isValidElement(child)) {
return cloneElement(child, { handleOpenDrawer });
}
return child;
});
return (
<DrawerLayout
ref={drawerRef}
drawerWidth={wp('60%')}
keyboardDismissMode="on-drag"
drawerPosition={DrawerLayout.positions.Left}
drawerType="front"
drawerBackgroundColor="white"
renderNavigationView={() => <RecordTypeFilters />}
edgeWidth={-wp('100%')}
>
<View style={styles.childrenContainer}>
{childrenWithProps}
</View>
</DrawerLayout>
);
}
Example #28
Source File: LeafletLayersControl.js From dash-leaflet with MIT License | 6 votes |
// ONLY MODIFICATION IS HERE
render() {
const children = Children.map(this.props.children, (child) => {
const clone = cloneElement(child, this.controlProps)
clone.props._dashprivate_layout.props = {...child.props._dashprivate_layout.props, ...this.controlProps};
return clone
})
return <Fragment>{children}</Fragment>
}
Example #29
Source File: Portal.js From tonic-ui with MIT License | 6 votes |
Portal = forwardRef(
({ children, container, isDisabled = false, onRendered }, ref) => {
const [mountNode, setMountNode] = useState(null);
const handleRef = useMergeRefs(children.ref, ref);
useIsomorphicEffect(() => {
if (!isDisabled) {
setMountNode(getContainer(container) || document.body);
}
}, [container, isDisabled]);
useIsomorphicEffect(() => {
if (mountNode && !isDisabled) {
assignRef(ref, mountNode);
return () => {
assignRef(ref, null);
};
}
return undefined;
}, [ref, mountNode, isDisabled]);
useIsomorphicEffect(() => {
if (onRendered && (mountNode || isDisabled)) {
onRendered();
}
}, [onRendered, mountNode, isDisabled]);
if (isDisabled) {
Children.only(children);
return cloneElement(children, {
ref: handleRef,
});
}
return mountNode ? createPortal(children, mountNode) : mountNode;
},
)