@react-transformer/replacer
v1.0.20
Published
Transform simple string patterns to React components
Downloads
6
Maintainers
Readme
Convert string text to React components
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>,
)