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
optionalstringvariant
default:"information"
Style variant, one of
"information"
(blue),"success"
(green),"warning"
(orange), and"error"
(red).
requiredReact node or React node[]children
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:
const response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');const hipsterIpsum = response.json();
CodeExample props
optionalstringtitle
default:''
(empty string)Title appearing in the top bar of the CodeExample container.
optionalstring[]labels
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.
requiredReact node or React node[]children
MDX code blocks placed between CodeExample tags.
ExternalLink
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'
:
You can also use the component directly if you prefer:
ExternalLink props
requiredstringhref
External URL that will open in a new tab when the link is clicked.
optionalbooleanshowIcon
default:true
Whether to show the new-window icon. You might not want the icon for non-text links such as images.
requiredReact nodechildren
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
requiredstringsrc
Filename of the image asset (must live in your site's designated assets folder, such as
src/assets
). Do not include the path.
optionalstringalt
default:''
(empty string)Text that describes the image.
optionalstringtitle
default: value ofalt
propText 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
:
---title: Table of contentsdescription: Demonstration of the PostList componentshowTOC: 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
optionalstring
title
default:''
(empty string)Title that appears in the header of the table.
requiredReact node or React node[]
children
Markdown table placed between PropertyTable tags. Table headers should be
Name
,Type
,Info
,Default
, and/orDescription
(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
optional (default value:
type
'array'
)stringType of the resource, one of
'array'
or'object'
.requiredstring
owner
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
optionalnumberdepth
default:6
Depth of nested items to print (between
2
and6
).
optionalobjectcontents
default:null
Custom table of contents with the following shape:
{ items: [{ title: '', url: '' }] }
. Used by other components.
optionalstringtitle
default:''
(empty string)Title displayed above the list of contents.
optionalstringclassName
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
requiredReact node or React node[]children
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:
---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']}>```jsconst response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');const hipsterIpsum = response.json();``````shcurl -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.
const response = await fetch('https://hipsum.co/api/?type=hipster-centric&sentences=3');const hipsterIpsum = response.json();
[ "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.
Internal and External Links
There are three link types with different behaviors on a Chicago Docs site:
Type | Behavior | Path | Component | Example |
---|---|---|---|---|
External link | Opens in a new tab and includes a new-window icon. | Starts with 'http' | ExternalLink | GitHub |
Internal link | Navigates to other pages on the same site without a page refresh. | Relative path (e.g., /docs/quick-start/ ) | Gatsby Link | Quick Start |
Fragment link | Jumps to a different location on the same page without a page refresh. | Fragment path (e.g., #theme-ui-components ) | <a> tag | Code |
Create a Markdown link in an MDX file, and the appropriate link type will be used:
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:
123456789
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 (-
):
123456789
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:
Hook | Parameters | Purpose | Core |
---|---|---|---|
useDocContext | Fetches the docId and sidebar menu object for the current doc. | No | |
useDocData | Fetches all data for all docs using a GraphQL query (see below). | Yes | |
useLocation | Fetches the browser's location object. | No | |
usePrismTheme | Fetches the current Prism theme (according to the current color mode). | No | |
useSiteMetadata | Fetches 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 |
useThemeOptions | Fetches 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:
idtitleshortTitledescriptionpathslugexcerptbodyshowBreadcrumbshowPostNavshowSidebarshowTOC
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:
123456789101112131415161718
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>);}