Understanding how to show or hide a text field based on a boolean in Sanity.io.
11 replies
Last updated: Oct 11, 2022
S
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
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
},
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
The code you’ve constructed makes use of a callback function that’s returning
As for your request for better solutions, we recommend optional chaining in case
user R
!The code you’ve constructed makes use of a callback function that’s returning
trueor
falseto your
entryfield’s
hiddenproperty.
({document}) => !document.flagis destructuring
documentfrom the argument being passed to the callback function, which gives you access to the value of the
flagfield. If
flagis true, then
!document.flagis false, which means
entrywill not be hidden. If
flagis false (or indeterminate and therefore undefined),
!document.flagis true, which means
entrywill be hidden.
As for your request for better solutions, we recommend optional chaining in case
documentis undefined (so
!document.flagbecomes
!document?.flag). You may also want to confirm that the behaviour you’re getting when
flagis indeterminate (e.g., unset or “in the middle”) is what you want. Undefined is falsy so
!flagwill resolve to
truewhen
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
S
Thank you
user A
for your explanation.Oct 11, 2022, 7:32 PM
S
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
S
as i understand from your answer. is this the right way that i should define the code ?
Oct 11, 2022, 7:36 PM
S
the output was this
Oct 11, 2022, 7:36 PM
S
thanks for your time and help.really appreciate it
😊 👍
😊 👍
Oct 11, 2022, 7:43 PM
S
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.