react#cloneElement JavaScript Examples
The following examples show how to use
react#cloneElement.
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 |
deepFilter = (children, deepFilterFn) => Children.toArray(children)
.filter(deepFilterFn)
.map((child) => {
if (isValidElement(child) && hasComplexChildren(child)) {
// Clone the child that has children and filter them too
return cloneElement(child, {
...child.props,
children: deepFilter(child.props.children, deepFilterFn),
});
}
return child;
})
Example #2
Source File: utils.js From hzero-front with Apache License 2.0 | 7 votes |
export function getQueryFields(dataSet) {
const {
props: { queryFields },
} = dataSet;
const queryDataSet = dataSet.queryDataSet || dataSet.props.queryDataSet;
const result = [];
if (queryDataSet) {
const fields = queryDataSet.fields || queryDataSet.props.fields;
return [...fields.entries()].reduce((list, [name, field]) => {
if (!field.get('bind')) {
const props = {
key: name,
name,
dataSet: queryDataSet,
};
const element = queryFields[name];
list.push(
isValidElement(element)
? cloneElement(element, props)
: cloneElement(getEditorByField(field), {
...props,
...(isObject(element) ? element : {}),
})
);
}
return list;
}, result);
}
return result;
}
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: 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 #5
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 #6
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 #7
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 #8
Source File: Transition.js From smart-contracts with MIT License | 6 votes |
// ----------------------------------------
// Render
// ----------------------------------------
render() {
debug('render(): props', this.props)
debug('render(): state', this.state)
const { children } = this.props
const { status } = this.state
if (status === TRANSITION_STATUS_UNMOUNTED) {
return null
}
return cloneElement(children, {
className: this.computeClasses(),
style: this.computeStyle(),
})
}
Example #9
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 #10
Source File: DockMonitor.js From Learning-Redux with MIT License | 6 votes |
renderChild(child, index, otherProps) {
const { monitorState } = this.props;
const { childMonitorIndex, childMonitorStates } = monitorState;
if (index !== childMonitorIndex) {
return null;
}
return cloneElement(child, {
monitorState: childMonitorStates[index],
...otherProps
});
}
Example #11
Source File: FooterBottom.js From react-dsfr with MIT License | 6 votes |
FooterBottom = ({ children, className, ...remainingProps }) => {
const links = Children.toArray(children)
.filter((link) => link.props.__TYPE === 'FooterLink')
.map((link) => cloneElement(link, { section: 'bottom' }));
const childs = Children.toArray(children).filter((link) => link.props.__TYPE !== 'FooterLink');
return (
<div
className={classNames('fr-footer__bottom', className)}
{...dataAttributes.getAll(remainingProps)}
>
<ul className="fr-footer__bottom-list">
{links}
</ul>
{childs}
</div>
);
}
Example #12
Source File: Transition.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
// ----------------------------------------
// Render
// ----------------------------------------
render() {
debug('render()')
debug('props', this.props)
debug('state', this.state)
const { children } = this.props
const { status } = this.state
if (status === Transition.UNMOUNTED) return null
return cloneElement(children, {
className: this.computeClasses(),
style: this.computeStyle(),
})
}
Example #13
Source File: ToggleButton.js From wix-style-react with MIT License | 6 votes |
render() {
const {
skin,
children,
selected,
dataHook,
tooltipContent,
tooltipProps,
...rest
} = this.props;
return (
<Tooltip
upgrade
{...tooltipProps}
size="small"
content={tooltipContent}
data-hook={dataHook}
>
<ButtonNext
{...rest}
{...styles('root', { skin, selected }, rest)}
data-hook="togglebutton-trigger"
data-selected={selected}
data-skin={skin}
>
{children &&
cloneElement(children, {
width: childSize,
height: childSize,
})}
</ButtonNext>
</Tooltip>
);
}
Example #14
Source File: index.jsx From mixbox with GNU General Public License v3.0 | 6 votes |
render() {
let {
right,
sideWidth,
sideCollapsedWidth,
sideCollapsed,
style = {},
styleName,
children,
action,
...others
} = this.props;
sideWidth = sideCollapsed ? sideCollapsedWidth : sideWidth;
style = {left: sideWidth, textAlign: right ? 'right' : 'left', ...style};
styleName = styleName ? `${styleName} fix-bottom` : 'fix-bottom';
return (
<div
{...others}
styleName={styleName}
style={style}
>
{React.Children.map(children, item => {
// 如果子元素是antd button ,自动处理间距
if (item && item.type.__ANT_BUTTON) {
let style = right ? {marginLeft: '8px'} : {marginRight: '8px'};
style = {...style, ...item.props.style};
return cloneElement(item, {style});
}
return item;
})}
</div>
);
}
Example #15
Source File: Oneof.js From dm2 with Apache License 2.0 | 6 votes |
Oneof = ({ value, children, className }) => {
const selectedChild = useMemo(() => {
if (Array.isArray(children)) {
return children.find(c => compareCase(value, c.props.case)) || null;
} else if (compareCase(value, children.props.case)) {
return children;
}
}, [children, value]);
return selectedChild ? cloneElement(selectedChild, {
...selectedChild.props,
className: [className, selectedChild.props.className].join(" "),
}) : null;
}
Example #16
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 #17
Source File: Dropdown.jsx From kube-design with MIT License | 6 votes |
render() {
const { className, children, onClick, theme, ...restProps } = this.props;
const isTriggerValid = isValidElement(children);
return (
<Popper
{...restProps}
type="dropdown"
className={classNames("dropdown", `dropdown-${theme}`, className)}
onClick={onClick}
>
{isTriggerValid ? (
cloneElement(children, {
className: classNames("is-trigger", children.props.className),
})
) : (
<span className="is-trigger">{children}</span>
)}
</Popper>
);
}
Example #18
Source File: nav-link.js From dashboard with MIT License | 6 votes |
A = forwardRef(({ children, icon, ...props }, ref) => {
const color = useColorModeValue('gray.500', 'gray.300');
return (
<Flex
ref={ref}
as="a"
w="full"
align="center"
cursor="pointer"
px={3}
py={2}
fontWeight="medium"
color={color}
borderRadius="md"
outline="none"
_focus={{ shadow: 'outline' }}
_notFirst={{ mt: 1 }}
{...props}
>
{icon && cloneElement(icon, { mr: 3 })}
<Box w="full">{children}</Box>
</Flex>
);
})
Example #19
Source File: ChildMapping.js From mern_docker_demo with MIT License | 6 votes |
export function getInitialChildMapping(props, onExited) {
return getChildMapping(props.children, function (child) {
return cloneElement(child, {
onExited: onExited.bind(null, child),
in: true,
appear: getProp(child, 'appear', props),
enter: getProp(child, 'enter', props),
exit: getProp(child, 'exit', props)
});
});
}
Example #20
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 递归遍历 react 节点
* @param {array} children - react node
* @param {function} fn - 回调函数
*/
@Bind()
mapReactChildren(children, fn) {
return React.Children.map(children, child => {
if (!isValidElement(child)) {
return child;
}
if (child.props.children) {
// eslint-disable-next-line
child = React.cloneElement(child, {
children: this.mapReactChildren(child.props.children, fn),
});
}
return fn(child);
});
}
Example #21
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 #22
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 #23
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 #24
Source File: cloneWithRef.js From the-eye-knows-the-garbage with MIT License | 6 votes |
export function cloneWithRef(element, newRef) {
var previousRef = element.ref;
invariant(typeof previousRef !== 'string', 'Cannot connect React DnD to an element with an existing string ref. ' + 'Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. ' + 'Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute');
if (!previousRef) {
// When there is no ref on the element, use the new ref directly
return cloneElement(element, {
ref: newRef
});
} else {
return cloneElement(element, {
ref: function ref(node) {
setRef(previousRef, node);
setRef(newRef, node);
}
});
}
}
Example #25
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;
},
)
Example #26
Source File: ChatHead.jsx From matx-react with MIT License | 6 votes |
ChatHead = ({ icon, children }) => {
const [open, setOpen] = useState(false);
const togglePopup = async () => {
setOpen((open) => !open);
};
return (
<PopupRoot>
{cloneElement(icon, { onClick: togglePopup })}
<Popup className={clsx({ popupOpen: open })}>
{open ? cloneElement(children, { togglePopup }) : null}
</Popup>
</PopupRoot>
);
}
Example #27
Source File: CodeExamples.jsx From vertx-web-site.github.io with Apache License 2.0 | 6 votes |
CodeExamples = ({ wide, children } ) => {
let titles = Children.map(children, c => c.props.title)
const [active, setActive] = useState(titles[0])
return (
<div className={classNames("code-examples", { wide })}>
<div className="code-examples-tabs">
{titles.map(title => (
<div className={classNames("code-examples-tab", { active: active === title })}
onClick={() => setActive(title)} key={title}>{title}</div>
))}
</div>
<div className="code-examples-content">
{Children.map(children, child => cloneElement(child, {
active: active === child.props.title
}))}
</div>
<style jsx>{styles}</style>
</div>
)
}
Example #28
Source File: Overflow.jsx From awesome-react-starter with MIT License | 6 votes |
Overflow = ({ children }) => {
const append = (child) => {
const className = classnames(child.props.className, 'truncate');
const props = {
...child.props,
title: child.props.children,
className,
};
return cloneElement(child, props);
};
return <div className="overflow-hidden truncate">{Children.map(children, append)}</div>;
}
Example #29
Source File: Overlay.js From vindr-lab-viewer with MIT License | 6 votes |
render() {
const { animation, children, ...props } = this.props;
const transition = animation === true ? Fade : animation || null;
let child;
if (!transition) {
child = cloneElement(children, {
className: classNames(children.props.className, 'in'),
});
} else {
child = children;
}
return (
<BaseOverlay {...props} transition={transition}>
{child}
</BaseOverlay>
);
}