Conditionally wrap a group of React elements with a passed wrapper if the condition is true.

Parameters:
NameTypeDescription
conditionboolean | string/number

The condition to compare against, bool, empty string etc.

wrapperfunction

The wrapper.

childrenJSX.ElementChildrenAttribute | JSX.Element

The children as jsx.

Since
  • 1.0.1
Returns:
Type: 
*
Example
import { ConditionalWrapper } from '@gravityforms/react-utils';

export default function Loader( {
	background = '',
	children = null,
	customAttributes = {},
	customClasses = [],
	displayText = true,
	foreground = '',
	lineWeight = 5,
	mask = false,
	maskCustomAttributes = {},
	maskCustomClasses = {},
	maskTheme = 'light',
	size = 40,
	spacing = '',
	speed = 2,
	text = '',
	textColor = '#000',
	textCustomAttributes = {},
	textCustomClasses = {},
	type = 'ring',
} ) {
	const maskProps = mask ? {
		className: classnames( {
			'gform-loader__mask': true,
			[ `gform-loader__mask--theme-${ maskTheme }` ]: true,
		}, maskCustomClasses ),
		...maskCustomAttributes,
	} : {};

	const componentProps = {
		className: classnames( {
			'gform-loader': true,
			[ `gform-loader--${ type }` ]: true,
			...spacerClasses( spacing ),
		}, customClasses ),
		...customAttributes,
	};

	const textProps = text ? {
		className: classnames( {
			'gform-loader__text': displayText,
			'gform-visually-hidden': ! displayText,
		}, textCustomClasses ),
		style: {
			color: textColor,
		},
		...textCustomAttributes,
	} : {};

	const getLoader = () => {
		switch ( type ) {
			case 'ring':
				return (
					<Ring
						background={ background }
						componentProps={ componentProps }
						foreground={ foreground }
						lineWeight={ lineWeight }
						size={ size }
						speed={ speed }
					/>
				);
			default:
				return (
					<span { ...componentProps } />
				);
		}
	};

	return (
		<>
			<ConditionalWrapper
				condition={ mask }
				wrapper={ ( ch ) => <div { ...maskProps }>{ ch }</div> }
			>
				<ConditionalWrapper
					condition={ ! mask && text && displayText }
					wrapper={ ( ch ) => <span className="gform-loader__inner">{ ch }</span> }
				>
					{ getLoader() }
					{ text && <span { ...textProps }>{ text }</span> }
					{ children }
				</ConditionalWrapper>
			</ConditionalWrapper>
		</>
	);
}