Giter Club home page Giter Club logo

react-interpolate's Introduction

react-interpolate

size Actions Status

A string interpolation component that formats and interpolates a template string in a safe way.

import Interpolate from '@doist/react-interpolate'

function Greeting() {
    return (
        <Interpolate
            string="<h1>Hello {name}. Here is <a>your order info</a></h1>"
            mapping={{
                name: 'William',
                a: <a href="https://orderinfo.com" />,
            }}
        />
    )
}

Would render the following HTML

<h1>Hello William. Here is <a href="https://orderinfo.com">your order info</a></h1>

Component API

<Interpolate> component accepts the following props

string

The template string to be interpolated. Required.

Please see the Interpolation syntax section below for more detail.

mapping

An object that defines the values to be injected for placeholder and tags defined in the template string. Optional.

  • For placeholder or self-closing tag, the mapping value could be any valid element value
  • For open & close tag, the mapping value could be either renderer function or an element.
<Interpolate
    string="Hello {name}. Here is <orderLink>your order info</orderLink><hr/>.  \
            Please contact <supportLink>support</supportLink> for help"
    mapping={{
        // you can map placholder and self-closing tag to any valid element value
        name: 'William',
        hr: <hr className="break" />,

        // you can map open & close tag to a rendering function
        orderLink: (text) => <a href="https://orderinfo.com">{text}</a>,

        // or you can map open & close tag to an element
        supportLink: <a href="https://orderinfo.com" />,
    }}
/>

graceful

A boolean flag indicates how string syntax error or mapping error should be handled. When true, the raw string value from the prop string would be rendered as a fallback in the error scenario. When false, error would be thrown instead.

Optional. true by default.

// would render "an invalid string with unclose tag &lt;h1&gt;"
<Interpolate graceful string="an invalid string with unclose tag <h1>" />

syntax

Optional. syntax props allow use of react-Interpolate with different string formatting syntax. Please see the "Custom syntax support" section for more detail.

Interpolation syntax

Here is interpolation syntax you can use in your string.

Placeholder

'hello {user_name}'

Placeholder name should be alphanumeric ([A-Za-z0-9_]). Placeholders could be mapped to any valid element value.

Open & close tags

'Here is <a>your order info</a>'

// tag name could be any alphanumeric string
'Here is <link>your order info</link>'

// you can nest tag and placeholder
'Here is <a><b>you order info {name}</b></a>'

Tag name should be alphanumeric ([A-Za-z0-9_]).

Open & close tag could be mapped to an element value.

<Interpolate
    string="Here is <a>your order info</a>"
    mapping={{
        a: <a href="https://orderinfo.com" />
    }}
/>


// Invalid; the mapping value element should not contain children
<Interpolate
    string="Here is <a>your order info</a>"
    mapping={{
        a: (
            <a href="https://orderinfo.com">
                <b />
                <br />
            </a>
        )
    }}
/>

Open & close tag could be mapped to a rendering function, which would take a single argument that contains the enclosing text.

<Interpolate
    string="Here is <a>your order info</a>"
    mapping={{
        a: (text) => (
            <a href="https://orderinfo.com">
                <b>{text}</b>
                <br />
            </a>
        ),
    }}
/>

Unclosed tag or incorrect nesting of tag would result in syntax error.

// bad: no close tag
'Here is <a>your order info'

// bad: incorrect tag structure
'Here is <a><b>your order info</a></b>'

Self closing tag

'Hello.<br/>Here is your order'

Tag name should be alphanumeric ([A-Za-z0-9_]). Self closing tags could be mapped to any valid element value.

Auto tag element creation

When tags are used the string but there are no correponding mapped value, it would by default create the corresponding HTML element by default.

// would render: <h1>Hellow</h1><br/>World
<Interpolate string="<h1>Hello</h1><br/>world" />

Custom syntax support

You may already be using a formatting syntax in your string that is different than the built-in syntax support from Interpolate. You can configure Interpolate so that it could recognize the formatting syntax that you use.

For instance, you may be using i18next which has a slightly different placeholder syntax.

hello {{name}}

You can define the formatting syntax of your string via syntax props.

import Interpolate, { TOKEN_PLACEHOLDER } from "react-interpolate"

const i18nNextSyntax = [
    {
        type: TOKEN_PLACEHOLDER,
        regex: /{{\s*(\w+)\s*}}/g
    }
]

// will output "hi steven"
<Interpolate
    syntax={i18nNextSyntax}
    string="hi {{name}}"
    mapping={{
        name: "steven"
    }}
/>

react-interpolate comes with i18next syntax support, and you can enable it via

import { SYNTAX_I18NEXT } from "react-interpolate"

<Interpolate
  syntax={SYNTAX_I18NEXT}
  ...
/>

Releasing

A new version of @doist/react-interpolate is published both on npm and GitHub Package Registry whenever a new release on GitHub is created.

To update the version in both package.json and package-lock.json run:

npm --no-git-tag-version version <major|minor|patch>

Once these changes have been pushed and merged, create a release on GitHub.

A GitHub Action will automatically perform all the necessary steps and will release the version number that's specified inside the package.json's version field so make sure that the release tag reflects the version you want to publish.

react-interpolate's People

Contributors

antonjb avatar deorus avatar dependabot[bot] avatar henningmu avatar miottid avatar pedroalves0 avatar stkao05 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

stkao05 sam-lord

react-interpolate's Issues

Won't install with node v16.14

When using node v16.14, it won't install.

yarn add @doist/react-interpolate
yarn add v1.22.18
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
error @doist/[email protected]: The engine "node" is incompatible with this module. Expected version "16.13". Got "16.14.2"
error Found incompatible module.

Add a license to this code

Please could you add an open source license to this code?

I'm guessing it's meant to be open source, but without any license file or entry in package.json it's hard to tell the intention.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.