1.1.0 • Published 8 months ago

preact-body-class v1.1.0

Weekly downloads
6
License
MIT
Repository
github
Last release
8 months ago

preact-body-class

NPM version Downloads Dependency status

Provides a declarative way to specify document.body.className in your preact app. Supports server-side usage too.

Built with Preact Side Effect.


Install

npm install --save react-body-class

Dependencies: Preact >= 8.2.0

What it looks like

import BodyClass from 'react-body-class';

const Basic = () => (
  <BodyClass class="helloworld">
    <h1>You ate a whole wheel of cheese?</h1>
  </BodyClass>
);
// -> document.body.className === "helloworld"

const Nested = () => (
  <BodyClass className="outside">
    <div>
      <BodyClass className="inside">
        <p>I‘m not even mad</p>
      </BodyClass>
    </div>
  </BodyClass>
);
// -> document.body.className === "outside inside"

const GoCrazy = () => (
  <BodyClass className={Array(8).join(''/0) + ' batman!'}>
    <h1>I'm impressed</h1>
  </BodyClass>
);
// -> document.body.className === "NaNNaNNaNNaNNaNNaNNaN batman!"

Note: Only supports a single child as props.

Server Usage

When using server-side, use BodyClass.rewind() after rendering components to string to retrieve the combined class name. Then chuck that into your HTML template.

Important: This component keeps track of mounted instances, so if you don't call BodyClass.rewind() you'll get a memory leak.