Skip to content

Commit

Permalink
Support for Helmet script props.
Browse files Browse the repository at this point in the history
Originally suggested in google/schema-dts#112

Wraps returned innerHTML with safeJsonLdReplacer as well, since Helmet
will similarly just pass innerHTML as-is to dangerouslySetInnerHTML.
  • Loading branch information
Eyas committed Jun 19, 2020
1 parent e18a895 commit 90d078e
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions src/json-ld.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@
import * as React from "react";
import { Thing, WithContext } from "schema-dts";

interface JsonLdOptions {
/** Adds indentation, white space, and line break characters to JSON-LD output. {@link JSON.stringify} */
space?: string | number;
}

/**
* Component that inline-includes a JSON-LD script where specified.
*
* @example
* For Example:
*
* ```tsx
* <JsonLd<Person>
* item={{
Expand All @@ -38,10 +44,8 @@ import { Thing, WithContext } from "schema-dts";
* />
* ```
*/
export class JsonLd<T extends Thing> extends React.Component<{
export class JsonLd<T extends Thing> extends React.Component<JsonLdOptions & {
item: WithContext<T>;
/** Adds indentation, white space, and line break characters to JSON-LD output. {@link JSON.stringify} */
space?: string | number;
}> {
render() {
return (
Expand All @@ -55,6 +59,32 @@ export class JsonLd<T extends Thing> extends React.Component<{
}
}

/**
* Produces a Helmet-style <script> prop for a given JSON-LD datum.
*
* For example:
*
* ```tsx
* <Helmet script={[
* helmetJsonLdProp<Person>({
* "@context": "https://schema.org",
* "@type": "Person",
* name: "Grace Hopper",
* alternateName: "Grace Brewster Murray Hopper",
* alumniOf: {
* "@type": "CollegeOrUniversity",
* name: ["Yale University", "Vassar College"]
* },
* knowsAbout: ["Compilers", "Computer Science"]
* }),
* ]} />
* ```
*/
export const helmetJsonLdProp = <T extends Thing>(item: WithContext<T>, options: JsonLdOptions = {}) => ({
type: "application/ld+json" as const,
innerHTML: JSON.stringify(item, safeJsonLdReplacer, options.space),
});

type JsonValueScalar = string | boolean | number;
type JsonValue =
| JsonValueScalar
Expand Down

0 comments on commit 90d078e

Please sign in to comment.