Zum Inhalt springen

WERK 12

Conditional content wrapper in Gatsby

Conditional content wrapper in Gatsby

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.js
import * as React from 'react';
import { GatsbyImage } from 'gatsby-plugin-image';
const ConditionalWrapper = ({ condition, wrapper, children }) =>
condition ? wrapper(children) : children
const 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 wrapper
condition={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