React (with Typescript) and CSS Modules
This is an example of a React component that uses Typescript, and the CSS modules approach to styling. I found this example in this tutorial:
Create a buttons folder in your components folder.
Inside the buttons folder, create a file named Button.module.css, put this code in it:
.btn{
padding: 8px 12px;
border-radius: 3px;
border: 0;
}
.btn-primary{
background-color: blue;
color: white;
}
.btn-secondary{
background-color: blue;
color: white;
}
.btn-danger{
background-color: blue;
color: white;
}
Now, in the buttons folder, create a file named Button.tsx, and put this code in it:
import styles from './Button.module.css'
interface Props {
children: string;
color?: 'primary' | 'secondary' | 'danger';
onClick: () => void;
}
export const Button = ({children, onClick, color='primary'}:Props) => {
return (
<button onClick={onClick} className={[styles.btn, styles['btn-' + color]].join(' ')}>
{children}
</button>
)
}
A few things to note about this code:
- It's importing the css module as styles, so the class names in the module are referenced with dot notation (or bracket notation). For example: styles.btn
- The Props interface defines 3 props (children, color, and onClick)
- The color prop is an enumerated string AND it defaults to 'primary'
- Notice the clever use of the join() array method which is used to set the className.