How to check boolean field value in React from Sanity schema?

7 replies
Last updated: Aug 24, 2022
I have a boolean set up in my schema type for certain blog posts - If I want to determine in my react code whether or not this boolean is true or false, how might I go about checking it to put out one message vs another?
AI Update

You can check the boolean field value in your React code by fetching it from Sanity and using conditional rendering. Here's how:

1. Query the boolean field with GROQ

When fetching your blog post data, make sure to include the boolean field in your query:

import { createClient } from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'production',
  apiVersion: '2024-01-01',
  useCdn: true,
})

// Fetch your blog post with the boolean field
const query = `*[_type == "blogPost" && _id == $postId][0]{
  title,
  content,
  yourBooleanField
}`

const post = await client.fetch(query, { postId: 'your-post-id' })

2. Use conditional rendering in React

Once you have the data, you can use standard JavaScript conditional logic:

function BlogPost({ post }) {
  return (
    <div>
      <h1>{post.title}</h1>
      
      {post.yourBooleanField ? (
        <p>This message shows when the boolean is true</p>
      ) : (
        <p>This message shows when the boolean is false</p>
      )}
      
      {/* Or using && for single condition */}
      {post.yourBooleanField && <p>Only shows when true</p>}
    </div>
  )
}

3. If using Next.js

If you're working with Next.js, you might use the sanityFetch helper from next-sanity:

import { sanityFetch } from '@/sanity/lib/client'

export default async function BlogPostPage({ params }) {
  const post = await sanityFetch({
    query: `*[_type == "blogPost" && slug.current == $slug][0]{
      title,
      yourBooleanField
    }`,
    params: { slug: params.slug }
  })
  
  return (
    <div>
      {post.yourBooleanField ? 
        <div>Boolean is true!</div> : 
        <div>Boolean is false!</div>
      }
    </div>
  )
}

The key is to include your boolean field in your GROQ query, and then use standard JavaScript/React conditional operators (? :, &&, or if/else) to render different content based on its value.

Show original thread
7 replies
What context are you using it?
One option is to use and if statement:

if (booleanSchema) {
  //do something if booleanSchema is true
} else {
  //do something if booleanSchema is false
}
In React, you can conditionally show things like this:

{ booleanSchema && <YourComponent> }
or

{ 
  booleanSchema ? <YourComponent> : <YourOtherComponent
}
Two separate notes that might come up as well, when evaluating

Appearing when defined:
New documents are created without schema-defined fields. This means that a boolean field in your schema will not immediately result in documents containing the boolean key. The key must be assigned a value for it to appear in a document. Make sure your front-end code treats a missing boolean value as false.

Truthy/falsy:
In GROQ you can handle missing booleans and false values equally like this *[_type == 'story' && featured != true] which would match stories where featured is false or missing (or to be fair, any other value that is not true).

Source: https://www.sanity.io/docs/boolean-type
Thanks both of you, the ? : worked here - I had actually made a mistake earlier in my code which is why it wasn't working initially. Thank you!
You may already be aware, but in case you're like me and still relatively new to all this, that middle alternative of
{ booleanSchema && <YourComponent> }
means "I only care if this is true, otherwise disregard"

Sometimes you're just looking for a defined type, or the existence of a value (or its length) and if it isn't there, you'd rather it not mount at all, or for the code not to bother.

I use it all the time because the situation comes up all the time and it feels silly to write


x + y = z ? "Do stuff" : ""
or


x + y = z ? "Do stuff" : null
I used to get annoyed in vanilla JavaScript when it would bend over backwards trying to use one of my variables when there was nothing there, and having to write things like
typeof(myThing) !== "undefined" is just a mess to look at haha
I just used the convention today multiple times to do conditional form fields. There
isn't a false value. I just want it to exist or not exist 😃
Thank you for including the extra information! I'm certain that will help me in the future. I'm just trying to see how all of this works right now. It's exciting because making mistakes is really showing me how all of this works
user S
Quite welcome! I have spent the past year making almost every mistake so I can be a good resource! I promise that if you stick with it, it will be worth it. I just spent the last day building a surprise thing in a rush (I got told about a last minute deadline we needed to hit that was unknown) and these sorts of tools enabled me to jus burn through it. Iterate on the work I'd already done to just make new stuff, and have it work and work well.
Getting to manifest ideas and bang out new versions quickly without being impeded feels like what I think the dev experience was
meant to be all along but it's like it's only now getting there for real.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?