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

How to Style a Portable Text Component With '@PortableText'

8 replies
Last updated: Feb 22, 2022
Hello again everyone! I am trying to style a portable text component with '@portabletext/react' and I can't make any sense of the documentation...
I have my components defined like so.

const ptComponents = {
    block: {
      h1: ({ value }: any) => {
        return <h1 className="whiteText">{value}</h1>;
      },
      p: ({ value }: any) => {
        return <p className="whiteText">{value}</p>;
      },
    },
  };
And I am passing the components to the Portable Text Component here.

<PortableText value={project.fulldesc} components={ptComponents} />
The styles are not being applied though. What am I doing wrong? I seriously can't make out how to do this:
https://github.com/portabletext/react-portabletext
Feb 21, 2022, 5:32 AM
Hi
user R
, in your code you pass value (that is an array of portable text blocks) to block which returns an error -
Objects are not valid as a React child
. If you pass
props
instead - your code should work.
Feb 21, 2022, 8:02 AM
const ptComponents = {
    block: {
      h1: ({ props }: any) => {
        return <h1 className="whiteText">{props}</h1>;
      },
      p: ({ props }: any) => {
        return <p className="whiteText">{props}</p>;
      },
    },
  };
Feb 21, 2022, 8:02 AM
Should be
({ children })
instead of
({ value })
, this should work:
const ptComponents = {
  block: {
    h1: ({ children }: any) => {
      return <h1 className="whiteText">{children}</h1>;
    },
    p: ({ children }: any) => {
      return <p className="whiteText">{children}</p>;
    },
  },
};
Feb 21, 2022, 1:18 PM
Okay, I have tried passing both props and children and neither of these are working either.
Feb 21, 2022, 5:27 PM
user R
, could you paste your blockContent schema. Are there’re elements with the
p
and
h1
values? 🙂
Feb 22, 2022, 7:32 AM
 export default {
  title: 'Block Content',
  name: 'blockContent',
  type: 'array',
  of: [
    {
      title: 'Block',
      type: 'block',
      styles: [
        { title: 'H1', value: 'h1'},
        { title: 'P', value: 'p'},
      ],
    }
  ],
};
Feb 22, 2022, 7:34 AM
Thank you all. My issue was that 'p' was not defined in my blockContent schema. It was defined as 'normal'. Everything is working as expected now!
Feb 22, 2022, 8:31 PM
Racheal, just to answer your question, the text would come through perfectly sized, but wouldn't apply my css coloring rules.
Feb 22, 2022, 8:53 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?