Here's a nice React tip for you.
When creating components using TypeScript (please use TS), always extend the props type with a
React.HTMLAttributes
(you can replace the DivElement with any other element you are returning from your JSX).
That will allow you to have all the properties for that component correctly typed, and you can pass them to the JSX element you are returning.
A handy use case is where we want to create a component with specific styles but make it extendible so that other consumers that install that component in their app will be able to override the styles we defined with their own styles.
According to the CSS specificity rules, for their styles to apply, you have to pass their className as the last one in order (since they are both using the class selector, the latest styles that appear are those who apply).
In the following snippet, you'll notice how we pass the className attribute we destruct from props and use the classNames library to join them nicely:
import React, { ReactNode } from "react";
import { Link } from "@teambit/base-react.navigation.link";
import { Arrow } from "./arrow";
import styles from "./styles.module.scss";
import classNames from "classnames";
export type BackButtonProps = {} & React.HtmlHTMLAttributes<HTMLDivElement>;
export function BackButton({ className, ...rest }: BackButtonProps) {
return (
<div
{...rest}
className={classNames(styles.backButtonContainer, className)}
>
<Link href="/blog">
<Arrow />
<span className={styles.backButtonText}>Back to Blog</span>
</Link>
</div>
);
}
As we said, it will allow users to pass their own styles, and if there are any conflicting styles, the consumers' classes will override the default styles.
Always think about who is going to consume your component. You will probably be the first one consuming it, but you never know who else will come after you and install your component—extendible Components FTW.
For more posts like this follow me on LinkedIn
I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).
Top comments (0)