🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to handle the error "Objects are not valid as a React child" when rendering an object in React.

3 replies
Last updated: Oct 5, 2021
Error: Objects are not valid as a React child (found: object with keys {_key, _type, children, markDefs, style}). If you meant to render a collection of children, use an array instead.
[3:52 PM] useEffect(() => {
    sanityClient
      .fetch(
        
*[_type == "home"]{
        title,
        weddingDate,
        description,
        coupleHighlight,
        coupleIntroDescription,
        bannerImages[]{
          asset ->{
            _id,
            url
          },
        },

        coupleIntroImage[]{
          asset ->{
            _id,
            url
          },
        },

      }
      )
      .then((data) => setSlide(data))
      .catch(console.error);
  }, []);
Oct 4, 2021, 2:53 PM
Hi Victor. How are you rendering out
coupleHighlight
? If you’re not already doing so, I expect you’ll need to
import BlockContent from '@sanity/block-content-to-react'
, set up a serializer (optional), and then render out
coupleHighlight
using the
BlockContent
component. I’m guessing at your naming convention but something like:

return (
  <>
    <BlockContent blocks={slide.coupleHighlight} serializers={serializers} />
  </>
);
Oct 5, 2021, 4:22 AM
Hi Victor. This error will occur when you’re trying to render out an object. You’ll want to use a tool like block-content-to-react to handle your portable text.
You will
import BlockContent from '@sanity/block-content-to-react'
, set up a serializer (optional), and then use the
BlockContent
component. I’m guessing at your naming convention but something like:

return (
  <>
    <BlockContent blocks={slide.coupleHighlight} serializers={serializers} />
  </>
);
Oct 5, 2021, 4:28 AM
Hi Victor. This error will occur when you’re trying to render out an object. You’ll want to use a tool like portable-text-to-react to handle your portable text.
You will
import BlockContent from '@sanity/block-content-to-react'
, set up a serializer (optional), and then use the
BlockContent
component. I’m guessing at your naming convention but something like:

return (
  <>
    <BlockContent blocks={slide.coupleHighlight} serializers={serializers} />
  </>
);
Oct 5, 2021, 4:28 AM

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?