Reputation: 21
I want to add elements in gatsby template file in some cases.
I am developing document site using gatsby, the document made by markdown file. Here is md files, and gatsby template. How can I add elements if the document has pinned=true condition??
---
title: "doc title"
date: "2020-06-01"
tags: ["some","tags"]
pinned: TRUE
---
document body.
import React from "react"
import { graphql } from "gatsby"
export default class DocsList extends React.Component {
render() {
const posts = this.props.data.allMarkdownRemark.edges
return (
<div>
{posts.map(({ node }) => {
const title = node.frontmatter.title || node.fields.slug
const tags = node.frontmatter.tags || node.fields.slug
const ispinned = node.frontmatter.pinned || node.fields.slug
return(
<p>{title}</p>
<p>{(tags || []).map(tags => (<span className="tags" key={tags}><FaHashtag />{tags}</span>))}</p>
// if the document has `pinned=true` attribute, show <span> tag below
<p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>
)
})}
</div>
)
}
}
export const query = graphql`
query docssListQuery($skip: Int!, $limit: Int!) {
allMarkdownRemark(
filter: {
fields: { collection: { eq: "manuals" } }
frontmatter: { published: { ne: false } }
}
sort: { fields: [frontmatter___date], order: DESC }
limit: $limit
skip: $skip
) {
edges {
node {
id
fields {
slug
}
frontmatter {
title
date
tags
pinned
}
excerpt
timeToRead
}
}
}
}
`;
Upvotes: 2
Views: 854
Reputation: 537
You should use conditional rendering. Change your code:
// if the document has `pinned=true` attribute, show <span> tag below
<p>{if {ispinned===true ? `<span>This is PINNED item</span>` }}</p>
to
// if the document has `pinned=true` attribute, show <span> tag below
<p>{ispinned ? `<span>This is PINNED item</span>`: null }</p>
Upvotes: 1
Reputation: 6006
<p>{isPinned && <span>This is PINNED item</span>}</p>
If isPinned
evaluates to true
, and since <span />
is truthy, then the value of the whole expression would be this span
, hence your desired result.
Upvotes: 1