I've been combing through docs and I can't seem to find a simple example of a conditional in gatsby that is NOT a renderer condition.
I'm looking to compare within a mapped object, which is handled in the render method: (basic pseudo code)
class someTemplate extends Component {
render() {
const someobject = this.props.data.someobject
return (
<div id="page-wrapper">
{someobject.map((layout, i) => {
return (
<div className={(i === 0 ? (`slideshow-item shown`) : (`slideshow-item`) )}>
{if(i === 1)}
show something
{else if(i === 2)}
show something else
{else}
show default
{/if}
</div>
)
})
}
</div>
)
}
}
So the ternary you see for the className works fine. But as an example I may have 15 items in the loop and I want to make sure I set classes for the first 3 items, for example. In my findings, I see a lot of people giving examples of conditional rendering outside the return statement, but I do not want to make the whole chunk of code conditional for a few simple classes.
Is this possible in gatsby.js or do I really need to break things apart into components to achieve something so simple?
The file gatsby-config. js / gatsby-config. ts defines your site's metadata, plugins, and other general configuration. This file should be in the root of your Gatsby site. You can author the file in JavaScript or TypeScript.
Gatsby enables developers to build fast, secure, and powerful websites using a React-based framework and innovative data layer that makes integrating different content, APIs, and services into one web experience incredibly simple.
Such conditions don't have anything to do with Gatsby itself. You are now in the JSX syntax world. You can write them like this:
<div className={i === 0 ? `slideshow-item shown` : `slideshow-item`}>
{i === 1 && <span>show something</span>}
{i === 2 && <span>show something else</span>}
{i > 2 && <span>show default</span>}
</div>
Also note that you need to return a node - thus the <span>
element in the above example (it could be any other valid node).
EDIT: Instead of <span>
element a React.Fragment can be used to avoid extra DOM elements:
{i === 1 && <>show something</>}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With