104

GitHub - developit/preact-slots: ? Render Preact trees into other Preact trees,...

 6 years ago
source link: https://github.com/developit/preact-slots
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

preact-slots

Render Preact trees into other Preact trees, like portals.

Install

preact-slots is available on npm:

npm install --save preact-slots

Usage

Define "holes" in your appliation using <Slot name="foo" />, then fill them using <SlotContent slot="foo">some content</SlotContent>:

import { SlotProvider, Slot, SlotContent } from 'preact-slots'

render(
    <SlotProvider>
        <div>
            <Slot name="foo">
                Some Fallback Content
            </Slot>
            <SlotContent slot="foo">
                Replacement Content
            </SlotContent>
        </div>
    </SlotProvider>
)

The above renders <div>Replacement Content</div>.

An extended example follows:

import { Slot, SlotContent, SlotProvider } from 'preact-slots'

const Header = () => (
    <header class="header">
        <Slot name="title">Slots Demo</Slot>
        <Slot name="toolbar">
            { items => items && <nav>{items}</nav> }
        </Slot>
    </header>
)

const EditPage = ({ page, content, onSave, onCancel }) => (
    <div class="page-editor">
        <SlotContent slot="title">Editing {page}</SlotContent>
        <SlotContent slot="toolbar">
            <button onClick={onSave}>Save</button>
            <button onClick={onCancel}>Cancel</button>
        </SlotContent>
        <textarea value={content} />
    </div>
)

render(
    <SlotProvider>
        <div class="app">
            <Header />
            <EditPage />
        </div>
    </SlotProvider>
)

Similar Libraries

Slots are a concept that has been around for a while.

In particular, @camwest's react-slot-fill is similar to preact-slots, but geared towards React.

License

MIT License © Jason Miller


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK