[](https://www.npmjs.com/package/react-as-prop) [](https://github.com/neet/react-as-prop/actions/workflows/ci.yml) [


Type-safe React utility that adds an ad-hoc prop for switching which HTML element to render, for developing flexible and semantic UI components.
Inspired by styled-component's as prop and Material UI's component prop.
```
yarn add react-as-prop
Adds as prop to the component specified in the argument.
- component ― Component to add as propfallback
- ─ Default element, such as button or div
Here is an example of your component definition.
`tsx
import { overridable } from "react-as-prop";
interface InternalButtonProps {
// ⚠️ NOTE: This prop is always needed
as: ElementType;
size: "small" | "large";
children?: ReactNode;
}
const InternalButton: FC
const { as: Component, size, children, ...rest } = props;
return (
// You always have to add {...rest} in the end to accept other props from the component overriding this one
} {...rest}>
{children}
);
};
// It is recommended to export only this part
export const Button = overridable(Button, "button");
export type ButtonProps = ComponentProps
`
Then, it can be overriden with another component
`tsx`
Almost same as overridable, but also supports type-safe forwardRef.
- fn ― A function that accepts props and forwardedReffallback
- ─ Default element, such as button or div
Here is an example of your component definition.
`tsx
import { overridableWithRef } from "react-as-prop";
interface InternalButtonProps {
as: ElementType;
size: "small" | "large";
children?: ReactNode;
}
const InternalButton: ForwardRefRenderFunction<
InternalButtonProps,
// Use unknown because you can override it
unknown
> = (props, forwardedRef) => {
const { as: Component, size, children, ...rest } = props;
return (
}
ref={forwardedRef}
{...rest}
>
{children}
);
};
export const Button = overridableWithRef(Button, "button");
export type ButtonProps = ComponentProps
`
Then, it can be overriden with another component
`tsx
const ref = useRef
`
A factory function that returns override and overridableWithRef with customized name for as prop.
- propName ― name of the prop to use instead of "as"
`tsx
import { configure } from "react-as-prop";
// Use "kind" for as-prop
const { overridable } = configure("kind");
const Button = overridable(InternalButton, "button");
;
``