Skip to content

An React hook for easier implementation for component slots in composite components

Notifications You must be signed in to change notification settings

kspeyanski/use-component-slot

Repository files navigation

The useComponentSlot hooks allows you to easily implement component slots in your React components.

Installation

pnpm:

pnpm add use-component-slot
npm install use-component-slot

yarn:

yarn add use-component-slot

API

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>
  );
};

Usage

There are a couple of use cases for the useComponentSlot.

Custom Component

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} />;
}

React Elements

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"}}>}
    />
  );
}

Strings

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" />;
}

About

An React hook for easier implementation for component slots in composite components

Resources

Stars

Watchers

Forks

Packages

No packages published