The useComponentSlot
hooks allows you to easily implement component slots in your React components.
pnpm:
pnpm add use-component-slot
npm install use-component-slot
yarn:
yarn add use-component-slot
The useComponentSlot
accepts a single argument, which can be either:
import { useComponentSlot } from "use-component-slot";
const Form = (props) => {
const [Input, inputProps] = useComponentSlot(props.input || "input");
return (
<form>
<Input type="text" name="name" {...inputProps} />
<Input type="text" name="surname" {...inputProps} />
<button>submit</button>
</form>
);
};
There are a couple of use cases for the useComponentSlot
.
You can utilize the useComponentSlot
hook to create custom components that can be used to either override or extend the default rendering.
const CustomInput = (props) => {
return (
<input
{...props}
placeholder={
props.name === "name" ? "Enter your name" : "Enter your surname"
}
/>
);
};
function App() {
return <Form input={CustomInput} />;
}
You can also pass a React element to the useComponentSlot
hook. This is useful when you want to override the default rendering of a component.
function App() {
return (
<Form
input={<input style={{color: "red"}}>}
/>
);
}
You can also pass a string to the useComponentSlot
hook. This is useful when you want to override the default rendering of a component.
function App() {
return <Form input="textarea" />;
}