Component Samples

A Component Sample is a standalone JavaScript module (ESM), with a default export that is a React component.

import * as React from "react";

export default () => <div>This is a Component Sample</div>

The Component Sample Module can be used in the following ways:

  • As a standalone page, to show the Component Sample without any context or explanation around it.
  • Loaded into an <Exhibit> in a documentation page, to illustrate how the component looks in various states.
  • Rendered as source code into a documentation page, to provide examples how to use the component.
  • Used as a semi-realistic placeholder in your application.
  • When made available as a standalone page, that page can be loaded in an iframe to illustrate responsive behaviour.

At the very least it's useful to have at least one sample. In fact, the Timvir CLI tool generates a basic sample when you create a new component. Besides the basic sample, consider other samples such as:

  • minimal: To illustrate the minimal amount of props that need to be provided.
  • empty: To show how the component looks in the empty state (ie. a list with zero items)
  • loading or error: Loading / error states for components which load data from a remote source.
  • anatomy: To visually illustrate the individual parts that the component is made out of.

Parametrized Samples

The sample component should not depend on any props. That allows it to be used as a standalone page. However sometimes you may want to be able to slightly tweak the sample so you can reuse the same sample module in the documentation page. For that purpose the sample may consume optional props and tweak itself accordingly.

For example, if you have a checkbox-like component and want to show it as checked, unchecked, disabled in the documentation page.

import * as React from "react";
import { Checkbox } from "..";

interface Props {
  initialState?: boolean;
  disabled?: boolean;
  label?: React.ReactNode;
}

export default ({ initialState, disabled, label }: Props) => {
  const [checked, setChecked] = React.useState(!!initialState);

  return (
    <Checkbox
      label={label || "LABEL"}
      disabled={disabled}
      state={checked}
      onChange={() => setChecked(!checked)}
    />
  );
};

Such an example you can use multiple times inside the documentation page:

import Basic from "../samples/basic"
import { Grid, Exhibit } from "timvir/blocks";

<Grid>
  <Exhibit caption="Unchecked">
    <Basic />
  </Exhibit>
  <Exhibit caption="Checked">
    <Basic initialState={true} />
  </Exhibit>
  <Exhibit caption="Disabled">
    <Basic disabled />
  </Exhibit>
  <Exhibit caption="Suuuuuper looooong label">
    <Basic label="Queen Daenerys Stormborn of the House Targaryen" />
  </Exhibit>
</Grid>