Const<CloneWithProps fallback={<span>No content</span>}>
{condition && <Input />}
</CloneWithProps>
export const CloneWithProps: FC<
PropsWithChildren<{
props?: Record<string, unknown>
fallback?: ReactElement,
}>
> = ({ children, fallback, props = {} }) => {
if (children == null) {
return <>{fallback}</>
}
if (!isValidElement(children)) {
return <>{children}</>
}
const safeProps = sanitizeProps(children, props);
const mergedProps = { ...(children.props as Record<string, unknown>), ...safeProps };
return cloneElement(children, mergedProps)
}
Safely clones a single React element with additional props.
childrenisnullorundefined, rendersfallback.childrenis not a valid React element, renders it as-is.childrenis a valid element, clones it with sanitized props.Prop sanitization rules:
nullandundefinedvalues are removed.