Conditional content wrapper in Gatsby
24.02.2023 | cawi

Sometimes you need a div wrapper, but not always? Then use a conditional content wrapper. But consider to make it fit according your needs.
// src/pages/some-page.jsimport * as React from 'react';import { GatsbyImage } from 'gatsby-plugin-image';const ConditionalWrapper = ({ condition, wrapper, children }) =>condition ? wrapper(children) : childrenconst SomePage = ({title, img, description}) => {return (<main className="page"><h1>Some Page</h1><div>{ img ? <GatsbyImage className={ 'img' } alt={ title } image={ img }/> : null}<ConditionalWrapper// if there is an image, condition is true, add a div wrappercondition={img}wrapper={children => (<div className={'wrapper'}>{children}</div>)}><h2>{title}</h2><p>{description}</p></ConditionalWrapper></div></main>);};export default SomePage;
Credits
Thanks for this article and solution with React How to conditionally wrap an element in React