1.0.20 • Published 12 months ago

@react-transformer/replacer v1.0.20

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Convert string text to React components

NPM version Build npm-typescriptLicense]github-license-url

Live Demo

Installation:

npm install @react-transformer/replacer --save

or

yarn add @react-transformer/replacer

Use case

Your application is rendering a text sourced from an api response as shown below

const response = {id: 'xyz', title: 'Universities', subTitle: 'Admissions are opening next week, so hurry up'}

You are rendering the data from response title and subtitle as shown below

<div>
  <h1>{response.title}</h1>
  <h2>{response.subTitle}</h2>
</div>

If the content maker wants to make the next week a link to another url, It is not possible in above case. But with React Transformer you are do it very easily as shown below

const response = {id: 'xyz', title: 'Universities', subTitle: 'Admissions are opening <<|link|'{"data":{"text":"New Button","url":"some-url"}}'|>>, so hurry up

Changes in code

import { Replacer } from '@react-transformer/replacer'
const Link = (props: {data: {text: string, url:string}}) => {
  const { text, url } = props.data

  return <a href={url}>{text}</a>
}
const config = {
        pattern: {
          prefix: '<<',
          suffix: '>>',
          seperator: '|',
        },
        elementTypes: {
          link: Link,
        },
      };
render(
  return (
    <Replacer config={config}>
      <h1>{response.title}</h1>
      <h2>{response.subTitle}</h2>
    </Replacer>
  );
)

Output

Universities Admissions are opening next week, so hurry up

Usage :

Add Replacer to your component within which you would like to replace text to react components:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { Replacer } from '@react-transformer/replacer'

const Button = (props: IComponent) => {
  const { text } = props.data

  return <button>{text}</button>
}

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
  <React.StrictMode>
    <Replacer
      config={{
        pattern: {
          prefix: '<<',
          suffix: '>>',
          seperator: '|',
        },
        elementTypes: {
          button: Button,
        },
      }}
    >
      <h1>Example</h1>
      <div>
        <p>{`<<|button|'{"data":{"text":"New Button"}}'|>>`}</p>
      </div>
    </Replacer>
  </React.StrictMode>,
)
1.0.19

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.13-test-0

1 year ago

1.0.16

1 year ago

1.0.11

1 year ago

1.0.20

12 months ago

1.0.14

1 year ago

1.0.13

1 year ago

1.0.12

1 year ago

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago