I have a React / TypeScript component. In Button.tsx:
type Props = {
type:
| "primary"
| "secondary"
| "tertiary"
}
const Button = React.FC<Props> = ({ type }) => {
const color = (() => {
switch (type) {
case "primary":
return 'red';
case "secondary":
return 'blue';
case "tertiary":
return 'green';
default:
throw new Error("A backgroundColor condition was missed");
}
})();
return(
<button style={{ background: color }}>Im a button</button>
)
}
Which I can use in other components. In Page.tsx:
const Page = () => {
return(
<div>
<h1>Heading</h1>
<Button type="primary" />
</div>
)
}
In Storybook I need to use all of the type values. In Button.stories.js:
const types = [
"primary",
"secondary",
"tertiary",
];
export const AllButtons = () => {
return(
types.map(type=>{
<Button type={type} key={type} />
})
)
}
Rather than having to repeat "primary", "secondary", "tertiary" is there a way I can export them from Button.tsx? That way if a new type is added the Storybook file will automatically have it.
I could use an enum in Button.tsx:
export enum Types {
primary = "primary",
secondary = "secondary",
tertiary = "tertiary",
}
type Props = {
type: Types;
};
However then components that use Button cant just pass a string, you would have to import the enum every time you used Button, which isn't worth the trade off. In Page.tsx:
import { Type } from './Button'
const Page = () => {
return(
<div>
<h1>Heading</h1>
<Button type={Type.primary} />
</div>
)
}