@vojtechportes/react-handlebars-renderer
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

React Handlebars Renderer

npm version

Why?

Because when you need to render externally loaded template (for example one fetched from api), parsing JSX is not very effective and also, there are really no libraries that would allow anonymous functions, arrow functions etc.

How?

This module is basically rendering memoized Handlebars tempaltes as React components.

It is also allowing you to register Handlebars partials using usePartials hook. It goes through array of partials and registers them inside useMemo.

That is it.

Example

import React from 'react'
import { Renderer, usePartials, PartialProps } from '@vojtechportes/react-handlebars-renderer'

const partials: PartialProps[] = [
  {
    name: 'list',
    content: `
      {{#each items}} {{! Each item is an "li" }}
        <li>
            {{url}}
            {{#if items}} {{! Within the context of the current item }}
            <ul>
            {{> list}} {{! Recursively render the partial }}
            </ul>
            {{/if}}
        </li>
      {{/each}}
    `,
  }
]

interface ItemProps {
  url: string;
  items?: ItemProps[];
}

interface ContextProps {
  test: string;
  items: ItemProps[];
}

const context: ContextProps = {
  text: 'Lorem Ipsum',
  items: [
    { url: '/abc', items: [
      { url: '/abc/def' },
    ] },
    { url: '/foo' },
  ]
}

const source = `
  <p>
    {{text}}
  </p>
  <ul>
    {{> list}}
  </ul>
`

const Foo: React.FC = () => {
  usePartials(partials)

  return (
    <Renderer
      context={context}
      source={source}
    />
  )

  /**
  Will output

  <p>Lorem Ipsum</p>
  <ul>
    <li>
      /abc
      <ul>
        <li>/abc/def</li>
      </ul>
    </li>
    <li>/foo</li>
  </ul>
  */
}

/@vojtechportes/react-handlebars-renderer/

    Package Sidebar

    Install

    npm i @vojtechportes/react-handlebars-renderer

    Weekly Downloads

    0

    Version

    0.1.2

    License

    MIT

    Unpacked Size

    26.6 kB

    Total Files

    22

    Last publish

    Collaborators

    • vojtechportes