Search code examples
gatsbycontentful

Display Contentful Banner if Boolean is True - Gatsby


I have created a content model called "Announcement Banner". I want to show the announcement if "display" is set to true. I have been able to query it and display the banner on the page by just querying {announcmentBanner}.. but now I am trying to have it only display if the boolean is true (or set to yes)

I feel like I am on the right track. Here is what my content model looks like: contentful content

Below is my code:

const Header = () => {
  const data = useStaticQuery(graphql`
    query {
      contentfulCarousel(title: { eq: "homepage" }) {
        Images {
          id
          gatsbyImageData
          description
        }
      }
      contentfulAnnouncementBanner {
        bannerMessage
        display
      }
    }
  `)
  const announcementBanner = data.contentfulAnnouncementBanner.bannerMessage
  return (
    <>
    
   {
   announcementBanner.display && 
   <div className="announcementBanner">
   <h2>{announcementBanner.bannerMessage}</h2>
   </div>
  }

any help would be great! Thank you!


Solution

  • You almost have it. The issue is in:

     const announcementBanner = data.contentfulAnnouncementBanner.bannerMessage
    

    You are getting bannerMessage while you whould get the parent node, contentfulAnnouncementBanner.

     const Header = () => {
       const data = useStaticQuery(graphql`
         query {
           contentfulCarousel(title: { eq: "homepage" }) {
             Images {
               id
               gatsbyImageData
               description
             }
           }
           contentfulAnnouncementBanner {
             bannerMessage
             display
           }
         }
       `);
       const announcementBanner = data.contentfulAnnouncementBanner;
       return (
         <>
           {announcementBanner.display && (
             <div className="announcementBanner">
               <h2>{announcementBanner.bannerMessage}</h2>
             </div>
           )}
         </>
       );
     };
    

    Watch out, I don't know if it's because of a wrong copy-paste in the question, but you had a wrong formatting and syntax issue.