Skip to content

Instantly share code, notes, and snippets.

@eivindml
Last active November 19, 2020 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eivindml/f2fcf4055b28986b0a00b53d0abc5e11 to your computer and use it in GitHub Desktop.
Save eivindml/f2fcf4055b28986b0a00b53d0abc5e11 to your computer and use it in GitHub Desktop.
import BlockContent from "@sanity/block-content-to-react";
interface ArticleProps {
content: Array<any>;
}
export default function Article(props: ArticleProps) {
return (
<>
<BlockContent
blocks={props.content}
renderContainerOnSingleChild
serializers={{
container: (props: any) => {
return <div className="article">{props.children}</div>;
},
list: (props: any) => {
return <ul className="ul">{props.children}</ul>;
},
listItem: (props: any) => {
return <li className="li">{props.children}</li>;
},
types: {
block: (props: any) => {
const { style = "normal" } = props.node;
if (style === "h1") {
return <h1 className="heading heading-1">{props.children}</h1>;
}
if (style === "h2") {
return <h2 className="heading heading-2">{props.children}</h2>;
}
if (style === "h3") {
return <h3 className="heading heading-3">{props.children}</h3>;
}
if (style === "blockquote") {
return (
<blockquote className="blockquote">
{props.children}
</blockquote>
);
}
if (style === "normal") {
return <p className="normal">{props.children}</p>;
}
// Fall back to default handling
return BlockContent.defaultSerializers.types.block(props);
}
}
}}
/>
<style jsx>
{`
.article * {
line-height: 1.65em;
}
/**
* Adds space after each "normal" section, which is an immediate child of main wrapper.
*/
.article > :not(.heading):not(:last-child) {
margin-bottom: 1em;
}
.heading {
font-size: 1.5em;
font-weight: 600;
margin-bottom: 0.25em;
}
/**
* Adds space before all headings, excepts when a heading follows another heading.
* This is to add a space between all types of "normal" content and all headings.
*/
.heading:not(:first-child) {
margin-top: 2em;
}
.heading + .heading {
margin-top: 0;
}
/** .article will be scoped, but need to mark elements as global. */
.article :global(li:before) {
content: "-";
margin-right: 0.5em;
}
.article :global(strong) {
font-weight: 600;
}
.article :global(em) {
font-style: italic;
}
.article :global(a) {
text-decoration: underline;
color: black;
opacity: 1;
transition: opacity 250ms ease-in-out;
}
.article :global(a:hover) {
opacity: 0.6;
}
`}
</style>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment