All files index.tsx

100% Statements 12/12
94.44% Branches 17/18
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                              7x 7x 7x 7x   7x 7x 5x 3x   2x             7x 7x   7x    
import React, { type PropsWithChildren } from 'react';
import { If } from './If';
 
export * from './If';
 
export interface OnlyWhenProps {
  /** A single child element */
  children: React.ReactElement;
  /** When true, children will rendered as is */
  when: boolean;
  /** This is working in combination with hiddenMode={"css"} */
  className?: string;
  /**
   * Determines how "react-only-when" should hide the child element
   * "null": Will not render the child
   * "display": Will render the child with display:none
   * "visibility": Will render the child with visibility:hidden
   * "css": Will render the child with a CSS class (you can pass it a custom className prop)
   */
  hiddenMode?: 'null' | 'display' | 'visibility' | 'css';
}
 
export default function OnlyWhen(props: PropsWithChildren<OnlyWhenProps>) {
  const { children, when, hiddenMode = 'null', className = 'w-hidden' } = props;
  const singleChild = React.Children.only(children);
  const { style, ...restOfChildProps } = singleChild.props;
  const extendedProps = { ...restOfChildProps };
 
  const keepNode = hiddenMode && hiddenMode !== 'null';
  if (keepNode) {
    if (hiddenMode === 'css') {
      extendedProps.className = `${extendedProps.className || ''} ${className || ''}`.trim();
    } else {
      extendedProps.style = {
        ...style,
        ...(hiddenMode === 'display' && { display: 'none' }),
        ...(hiddenMode === 'visibility' && { visibility: 'hidden' }),
      };
    }
  }
  const cloned = React.cloneElement(singleChild, extendedProps);
  const toHide = <If condition={keepNode}>{cloned}</If>;
 
  return when ? singleChild : toHide;
}