1.0.20 • Published 2 years ago
@react-transformer/replacer v1.0.20
Convert string text to React components
Live Demo
Installation:
npm install @react-transformer/replacer --saveor
yarn add @react-transformer/replacerUse 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 upChanges 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
2 years ago
1.0.18
2 years ago
1.0.17
2 years ago
1.0.13-test-0
2 years ago
1.0.16
2 years ago
1.0.11
2 years ago
1.0.20
2 years ago
1.0.14
2 years ago
1.0.13
2 years ago
1.0.12
2 years ago
1.0.10
3 years ago
1.0.9
3 years ago
1.0.8
3 years ago
1.0.7
3 years ago
1.0.6
3 years ago
1.0.5
3 years ago
1.0.4
3 years ago
1.0.3
3 years ago
1.0.2
3 years ago