Skip to content

Components and Hooks

Overview

This section lists the React components that are available to MDX files in the src/docs directory (or the docsPath defined in the theme options) of your Chicago Docs site. It also lists the available hooks that can be used in custom components to fetch data about your docs.

Chicago Docs Components

Chicago Docs comes with several components that help make it quick and easy for your users to find information on your product or API. Features such as site search and sidebar navigation mean your users won't get frustrated trying to find what they need. This section provides usage examples and a list of props accepted by each component.

Terminology

React components are added to MDX files using JSX tags (e.g., the <Alert> tag inserts the Alert component). In this section, a child is a block of Markdown text between JSX tags. These blocks of text are passed to the React component as a prop called children. There should be a blank line above and below each block of text.

A prop is a value passed to the React component directly.

In the following example, the text "Please pay attention to me!" is a child of the Alert component. The component displays this text inside the colored box.

On the other hand, variant is a prop; its value ("warning") is passed to the component to determine the background color of the Alert box (in this case, orange).

See also Guide to MDX: JSX Syntax.

Example Subheader

Alert

The Alert component creates a colored text box with a message. Try it out in the live example below.

Alert props

  • variant

    optional
    string
    default: "information"

    Style variant, one of "information" (blue), "success" (green), "warning" (orange), and "error" (red).

  • children

    required
    React node or React node[]

    MDX text placed between Alert tags. This text is rendered inside the Alert box.

The following variants are available:

CodeExample

The CodeExample component is used to display one or more code examples in a container. It was designed with API docs in mind. Create language-specific examples for calling an API method, and display them all in one place! Only one code example is displayed at a time; the user chooses an example from a select box at the top of the CodeExample component.

A copy button is also included.

This meta-example demonstrates the CodeExample component using the CodeExample component:

GET

const response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');
const hipsterIpsum = response.json();

CodeExample props

  • title

    optional
    string
    default: '' (empty string)

    Title appearing in the top bar of the CodeExample container.

  • labels

    optional
    string[]
    default: []

    Array of strings describing the language or other aspect of each code block (the number of labels should equal the number of code blocks and be in the same order). If more than one label is present, the labels are displayed in a select box allowing users to switch between examples. A single label will be displayed as text.

  • children

    required
    React node or React node[]

    MDX code blocks placed between CodeExample tags.

This component creates an external link that opens in a new tab, which is indicated by an external-window icon. This component is used automatically in docs for any Markdown or HTML links with an href attribute starting with 'http':

Wikipedia

You can also use the component directly if you prefer:

Cats and the Internet

ExternalLink props

  • href

    required
    string

    External URL that will open in a new tab when the link is clicked.

  • showIcon

    optional
    boolean
    default: true

    Whether to show the new-window icon. You might not want the icon for non-text links such as images.

  • children

    required
    React node

    MDX text placed between ExternalLink tags, used to display the link.

Image

The Image component from Chicago Docs uses gatsby-image to optimize and lazy load an image. This component renders a fluid image that adjusts to the size of your screen. You can also use the Img component from gatsby-image directly. See gatsby-image for guidance.

Photo by Aleksey Milov on Unsplash

Image props

  • src

    required
    string

    Filename of the image asset (must live in your site's designated assets folder, such as src/assets). Do not include the path.

  • alt

    optional
    string
    default: '' (empty string)

    Text that describes the image.

  • title

    optional
    string
    default: value of alt prop

    Text that appears in a tooltip when the image is moused over.

PostList

This component is intended to be used in the index.mdx file of a directory. It prints a list of posts in that directory. For example, placing this at your-site.com/tutorials/configuration/ will return a list of all posts with the base path of /tutorials/configuration/, such as /tutorials/configuration/how-to-configure-gatsby.mdx.

The following example demonstrates use of the PostList component in the index.mdx of a directory called tutorials:

src/docs/tutorials/index.mdx

MDX
---
title: Table of contents
description: Demonstration of the PostList component
showTOC: false
---
This component will print a list of docs in the `tutorials` directory, such as `src/docs/tutorials/how-to-install-ubuntu.mdx`.
## Table of contents:
<PostList />

PropertyTable

This table component provides a neat way of listing the properties or attributes of a React component or other entity. It wraps a regular Markdown table that has specific header values (Name, Type, Info, Default, and Description). In fact, it's used to create its own props table here:

PropertyTable props

  • title

    optional
    string
    default: '' (empty string)

    Title that appears in the header of the table.

  • children

    required
    React node or React node[]

    Markdown table placed between PropertyTable tags. Table headers should be Name, Type, Info, Default, and/or Description (order not important). Other table headers will be ignored.

If a value for the Default column is included, it will appear following the string 'default:'. You can get around this by omitting a default value and adding it elsewhere:

Resource properties

  • type

    optional (default value: 'array')
    string

    Type of the resource, one of 'array' or 'object'.

  • owner

    required
    string

    Owner of the resource.

TOC

The TOC component is added automatically to MDX files in src/docs (or the docsPath defined in the theme options) when the alwaysShowTOC theme option is set to true. This can be overriden by the showTOC frontmatter field for an individual doc.

You can also insert a TOC component in a doc directly. It will produce a TOC for the current file:

TOC props

  • depth

    optional
    number
    default: 6

    Depth of nested items to print (between 2 and 6).

  • contents

    optional
    object
    default: null

    Custom table of contents with the following shape: { items: [{ title: '', url: '' }] }. Used by other components.

  • title

    optional
    string
    default: '' (empty string)

    Title displayed above the list of contents.

  • className

    optional
    string
    default: '' (empty string)

    Class name added to the outer div tag, which also has a class name of 'toc-container'.

TwoColumnSection

The TwoColumnSection component creates a <section> HTML tag that is styled in a two-column layout, where the left column scrolls and the right column is sticky on wide screens. On smaller screens, the second column appears below the first column and is not sticky. The best use for this component is to organize API methods. Describe the method in the left column, and provide request and response examples (or other content) that remain stickied on the right.

TwoColumnSection props

  • children

    required
    React node or React node[]

    MDX text placed between TwoColumnSection tags. Each child can be any valid MDX text, but it works best with code blocks and CodeExample components.

Use a thematic break (<hr /> or ---) somewhere between the TwoColumnSection tags to separate the content for the two columns (i.e., content before and after this tag will be placed in the left and right columns, respectively).

This hipster-centric example helps demonstrate this component:

example.mdx

MDX
---
title: TwoColumnSection component demonstration
---
<TwoColumnSection>
Meh hammock shaman XOXO thundercats disrupt pork belly marfa shoreditch. Dreamcatcher single-origin coffee whatever taiyaki pinterest enamel pin. Man braid adaptogen flannel pickled, retro vice paleo letterpress brunch disrupt put a bird on it fam. Activated charcoal pour-over street art, taiyaki hell of four loko chia gluten-free distillery. Hammock thundercats kombucha pop-up af vexillologist 90's shoreditch woke chillwave. Bushwick single-origin coffee semiotics lo-fi lyft sriracha hammock kinfolk asymmetrical tattooed. Deep v meditation normcore, gentrify echo park copper mug distillery vice messenger bag tattooed direct trade.
Bicycle rights blog deep v celiac williamsburg wolf godard meggings. Bitters schlitz yuccie offal. Yuccie cray art party YOLO, tousled fashion axe semiotics artisan affogato fanny pack 8-bit deep v taiyaki asymmetrical paleo. YOLO pinterest fanny pack paleo, DIY viral taxidermy. Palo santo kale chips polaroid 8-bit. Letterpress actually mumblecore blog. Iceland waistcoat lomo kinfolk meditation bicycle rights selvage chia pop-up kale chips small batch.
---
<CodeExample title="GET" labels={['JavaScript', 'curl']}>
```js
const response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');
const hipsterIpsum = response.json();
```
```sh
curl -s 'https://hipsum.co/api/?type=hipster-centric&sentences=3'
```
</CodeExample>
<CodeExample title="RESPONSE">
```sh
[ "Taxidermy poutine post-ironic hexagon pug food truck banh mi subway tile paleo bespoke. Trust fund tilde sustainable fingerstache biodiesel adaptogen. Twee XOXO hoodie knausgaard snackwave butcher, cardigan etsy trust fund mumblecore kogi try-hard." ]
```
</CodeExample>
</TwoColumnSection>

This results in the following two-column section:

Meh hammock shaman XOXO thundercats disrupt pork belly marfa shoreditch. Dreamcatcher single-origin coffee whatever taiyaki pinterest enamel pin. Man braid adaptogen flannel pickled, retro vice paleo letterpress brunch disrupt put a bird on it fam. Activated charcoal pour-over street art, taiyaki hell of four loko chia gluten-free distillery. Hammock thundercats kombucha pop-up af vexillologist 90's shoreditch woke chillwave. Bushwick single-origin coffee semiotics lo-fi lyft sriracha hammock kinfolk asymmetrical tattooed. Deep v meditation normcore, gentrify echo park copper mug distillery vice messenger bag tattooed direct trade.

Bicycle rights blog deep v celiac williamsburg wolf godard meggings. Bitters schlitz yuccie offal. Yuccie cray art party YOLO, tousled fashion axe semiotics artisan affogato fanny pack 8-bit deep v taiyaki asymmetrical paleo. YOLO pinterest fanny pack paleo, DIY viral taxidermy. Palo santo kale chips polaroid 8-bit. Letterpress actually mumblecore blog. Iceland waistcoat lomo kinfolk meditation bicycle rights selvage chia pop-up kale chips small batch.

GET

const response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');
const hipsterIpsum = response.json();

RESPONSE

[ "Taxidermy poutine post-ironic hexagon pug food truck banh mi subway tile paleo bespoke. Trust fund tilde sustainable fingerstache biodiesel adaptogen. Twee XOXO hoodie knausgaard snackwave butcher, cardigan etsy trust fund mumblecore kogi try-hard." ]

Theme-UI Components

All Theme-UI components, such as Avatar and Message, are available to this theme. See the Theme UI Docs for a list of components.

Note that the Theme-UI Alert component is overriden by the Alert component from Chicago Docs.

There are three link types with different behaviors on a Chicago Docs site:

TypeBehaviorPathComponentExample
External linkOpens in a new tab and includes a new-window icon.Starts with 'http'ExternalLinkGitHub
Internal linkNavigates to other pages on the same site without a page refresh.Relative path (e.g., /docs/quick-start/)Gatsby LinkQuick Start
Fragment linkJumps to a different location on the same page without a page refresh.Fragment path (e.g., #theme-ui-components)<a> tagCode

Create a Markdown link in an MDX file, and the appropriate link type will be used:

Github

You can also use the Gatsby Link and ExternalLink components directly if you prefer.

Code

Overview

Code blocks can be added to your docs using markdown syntax:

const helloWorld = () => {
return 'Hello, World!'
}

The programming language (e.g., js) should be specified after the first three backticks (```) so that Prism.js can determine how to highlight the code. Since prism-react-renderer is used behind the scenes, Chicago Docs supports the languages supported by that plugin. These languages are listed here.

Chicago Docs also supports the mdx language for use in live previews of MDX:

Header

Home

Line highlighting, line numbers, and live preview are rendered through the metastring, which is the text that follows the three backticks and the language value as described above. For example, in ```js {3}, the metastring is {3} and adds highlighting to line 3 of the code block.

This section describes how to add line highlighting, line numbers, and live previews.

Line numbers

Add line numbers by adding num to the metastring:

1
2
3
4
5
6
7
8
9
if (Array.isArray(languages)) {
languages.forEach(language => {
if (languages[language]) {
console.log(language);
} else {
console.warn('This language does not exist!');
}
});
}

Line highlighting

Indicate the lines to be highlighted by adding them between curly braces ({}) to the metastring for the code block. To add separate line numbers, use commas (,). Do not add spaces between commas. To indicate a range of lines, use a hyphen (-):

1
2
3
4
5
6
7
8
9
if (Array.isArray(languages)) {
languages.forEach((language) => {
if (languages[language]) {
console.log(language);
} else {
console.warn('This language does not exist!');
}
});
}

Live preview

To enable a live preview using markdown syntax, the metastring should exactly equal 'live':

Hooks

This theme's React hooks are a convenient way to access data about your site or the current post. They allow you to access metadata, theme options, sidebar menus, and the table of contents. They're meant to be used in custom or shadowed components. Import them from @kabartolo/gatsby-theme-chicago-docs/src/hooks.

Note that the @kabartolo/gatsby-theme-chicago-docs-core theme also comes with some of these hooks (as noted in the table below).

Use these hooks in your custom components to fetch data:

HookParametersPurposeCore
useDocContextFetches the docId and sidebar menu object for the current doc.No
useDocDataFetches all data for all docs using a GraphQL query (see below).Yes
useLocationFetches the browser's location object.No
usePrismThemeFetches the current Prism theme (according to the current color mode).No
useSiteMetadataFetches the site metadata defined in gatsby-config.js.Yes
useTableOfContents{ depth = 6, docId = '', path = '' }Fetches the table of contents for all docs in an array of objects. Each object contains the doc id, a nested object of nested headers, and a flatMap array of all headers. Pass the docId or current path to get the contents for a specific doc. The depth value specifies the depth of the nested object (does not affect flatMap).Yes
useThemeOptionsFetches the Chicago Docs theme options defined in gatsby-config.js.Yes

The useDocData hook returns an array of nodes with the following information about each doc:

id
title
shortTitle
description
path
slug
excerpt
body
showBreadcrumb
showPostNav
showSidebar
showTOC

The following example demonstrates how these hooks can be used. You can call useDocData to get a list of all docs on your site. You can then create a navigable list of docs:

doc-list.js

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from 'react';
import { Link } from 'gatsby';
import { useDocData } from '@kabartolo/gatsby-theme-chicago-docs/src/hooks';
export default function DocList() {
const docs = useDocData();
return (
<ul>
{docs.map((doc) => (
<li key={doc.id}>
<a href={doc.path}>{doc.title}</a>
</li>
))}
</ul>
);
}