Search code examples
reactjsreact-component

Ternary Operator for non self-closing HTML element/React component


How can I choose between two non self-closing React components a la ternary operator? I'm creating a splash page and want to display either a background image or video. It would be easy if my bkgd image & video components had self-closing tags, but these components wrap all the content on the page.

This code doesn't work because BGVideo and ImageContainer don't have closing tags:

const SplashView = ({ videoSrc, imageSrc, overlayColor}) => {
   return (
        { videoSrc ? (
            <BGVideo src={videoSrc} bgColor={overlayColor}>
            ) : (
                <ImageContainer imgSrc={imageSrc} bgColor={overlayColor}>
                ) 
        }
            <SplashContentContainer>
                <Logo />
                <Link />
                <OtherChildrenComponents />
            </SplashContentContainer>
        {videoSrc ? </BGVideo> : </ImageContainer>}
  )
}

I want to avoid having to duplicate all child components in a ternary operator:

return (
        { videoSrc ? (
            <BGVideo src={videoSrc} bgColor={overlayColor}>
                <SplashContentContainer>
                    <Logo />
                    <Link />
                    <OtherChildrenComponents />
                </SplashContentContainer>
            </BGVideo>
            ) : (
                <ImageContainer imgSrc={imageSrc} bgColor={overlayColor}>
                    <SplashContentContainer>
                        <Logo />
                        <Link />
                        <OtherChildrenComponents />
                    </SplashContentContainer>
                </ImageContainer>
                ) 
        }
  )

Solution

  • You can store child components in variable to avoid duplication.

    const splash = (
        <SplashContentContainer>
            <Logo />
            <Link />
            <OtherChildrenComponents />
        </SplashContentContainer>
    );
    
    return (
        <>
            {videoSrc ? (
                <BGVideo src={videoSrc} bgColor={overlayColor}>{splash}</BGVideo>
            ) : (
                <ImageContainer imgSrc={imageSrc} bgColor={overlayColor}>{splash}</ImageContainer>
            )
        </>
    );