✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Understanding how to show or hide a text field based on a boolean in Sanity.io.

11 replies
Last updated: Oct 11, 2022
hi all !i'm new to sanity. this is so amazing to learn.

here is my question,

i need a text field to show and hide based on a boolean.
i changed a bit of code from
user A
"Conditional validation of string" and i endup with the below code and it worked.but i need to understand how this work. can someone please explain this to me.
if you have a better solution for this i also like to hear them too. thnx

{
name: "flag",
title: "Show or Hide",
type: "boolean",
},
{
name: "entry",
type: "string",
title: "Entry",
hidden: ({document}) => !document.flag
},
Oct 11, 2022, 5:21 PM
Welcome
user R
!
The code you’ve constructed makes use of a callback function that’s returning
true
or
false
to your
entry
field’s
hidden
property.
({document}) => !document.flag
is destructuring
document
from the argument being passed to the callback function, which gives you access to the value of the
flag
field. If
flag
is true, then
!document.flag
is false, which means
entry
will not be hidden. If
flag
is false (or indeterminate and therefore undefined),
!document.flag
is true, which means
entry
will be hidden.
As for your request for better solutions, we recommend optional chaining in case
document
is undefined (so
!document.flag
becomes
!document?.flag
). You may also want to confirm that the behaviour you’re getting when
flag
is indeterminate (e.g., unset or “in the middle”) is what you want. Undefined is falsy so
!flag
will resolve to
true
when
flag === undefined
.
Oct 11, 2022, 5:47 PM
Really nice job adapting some code for your own use. Looking forward to seeing what you continue to build. 😀
Oct 11, 2022, 5:48 PM
Thank you
user A
for your explanation.
Oct 11, 2022, 7:32 PM
i should telll you english not my main language. therefore sometimes its hard to understand something for first time.
Oct 11, 2022, 7:32 PM
I understand. If there is anything that is still unclear, please let us know.
Oct 11, 2022, 7:34 PM
as i understand from your answer. is this the right way that i should define the code ?
Oct 11, 2022, 7:36 PM
the output was this
Oct 11, 2022, 7:36 PM
That looks good to me. 👍
Oct 11, 2022, 7:42 PM
thanks for your time and help.really appreciate it
😊 👍
Oct 11, 2022, 7:43 PM
Our pleasure! 😁
Oct 11, 2022, 7:44 PM
user A
quick question.how do i find latest apiVersion for client.js ?
Oct 11, 2022, 8:21 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?