Check out the example
branch for all of this working in action.
Before getting started, let's make sure this is a workable project:
git init .
npm init -y
nvm use 7.2.0
yarn add react react-dom
- Playground for predictable, isolated development of React Components.
- "Stories" to describe different use-cases.
- Live-reloading.
- "Addons" (e.g. knobs, documentation, specs, backgrounds, etc.)
yarn add --dev @kadira/storybook
.stories/config.js
import { configure } from "@kadira/storybook";
const stories = require.context("..", true, /\.stories\.js$/);
configure(() => (
stories.keys().forEach((file) => stories(file))
), module);
$(yarn bin)/start-storybook -p 3000
- Create something in
src/components/MyForm/MyForm.stories.js
import React from "react";
import { storiesOf, action } from "@kadira/storybook";
storiesOf("MyForm", module)
.add("default", () => (
<p>Test!</p>
))
;
- Add
onChange
,onSubmit
events via theaction
helper.
--
- Co-locate styles alongside components.
- Abstract styles into a components for cleaner abstractions in the consumer.
- Auto-prefixing.
- Supports what CSS supports.
- DRYs up common styles.
yarn add styled-components
- Style a regular HTML element (e.g.
label
) in your component:
import styled from "styled-components";
const Label = styled.label`
background: #369;
border: none;
color: #fff;
&:hover {
cursor: pointer;
}
`;
- You can even wrap existing components via
styled(Component)
, as long as they accept theclassName
prop.
- State management using observables & mutable structures.
- Performant rendering of only affected components.
- Less "ceremony" than Redux.
yarn add mobx mobx-react
yarn add babel-preset-{latest,react,stage-2}
yarn add babel-plugin-transform-decorators-legacy
- Create
.babelrc
:
{
"plugins": ["transform-decorators-legacy"],
"presets": ["latest", "react", "stage-2"]
}
- Wrap your component with
@observer
:
import { observer } from "mobx-react";
@observer
export default class ...
- Add
@computed
&@observable
class properties to your component for internal state.
import { computed, intercept, observe, observable } from "mobx";
...
@observable email = ""
@computed get valid() {
return this.email.includes("@highereducation.com");
}
- Add
intercept
&observe
methods to sanitize input & fire events:
componentDidMount() {
intercept(this, "email", (change) => {
change.newValue = change.newValue.trimLeft().trimRight();
return change;
});
observe(this, "email", (value) => this.props.onChange({ email: value }));
}
- Built-in support for Babel.
- Snapshots.
- Fast with caching.
- Easy to adopt in existing projects.
yarn add --dev jest
$(yarn bin)/jest
- Add tests to
__tests__
in any folder in the usualdescribe
/it
structure. - Convert a
.toBe(...)
assertion to.toMatchSnapshot();
.
Snapshotting existing Storybook stories: