Dynamically create and render React components from strings at runtime, converting strings to React components for flexible UI generation.
npm install string-to-react-componentjs
with npm
$ npm install string-to-react-component @babel/standalone --save
with yarn
yarn add string-to-react-component @babel/standalone
`
$3
`js
// This will create a global function StringToReactComponent
`
Basic Example
`js
import StringToReactComponent from 'string-to-react-component';
function App() {
return (
{ (props)=>{
}
);
}
`
$3
- The given code inside the string should be a function.
- The code inside the string has access to the React object and for using useState, useEffect, useRef and ... you should get them from React object or pass them as data prop to the component:
`js
import {useState} from 'react';
import StringToReactComponent from 'string-to-react-component';
function App() {
return (
{ (props)=>{
}
);
}
`
Using Unknown Elements
`js
import StringToReactComponent from 'string-to-react-component';
import MyFirstComponent from 'path to MyFirstComponent';
import MySecondComponent from 'path to MySecondComponent';
function App() {
return (
{ (props)=>{
}
);
}
`
props
$3
- type : object
- required : No
- data object is passed to the component(which is generated from the string) as props
- example :
`js
import {useState} from 'react';
import StringToReactComponent from 'string-to-react-component';
function App() {
const [counter, setCounter] = useState(0);
const increase = () => {
setCounter(counter + 1);
};
return (
{ (props)=>{
}
);
}
`
$3
- type : object
- required : No
- default value : {presets: ["react"],sourceMaps: "inline"}
- See the full option list here
- examples :
- using typescript :
`js
babelOptions={{filename: 'counter.ts', presets: ['react', ['typescript', {allExtensions: true, isTSX: true}]]}}>
{()=>{
}
`
Caveats
This plugin does not use eval function, however, suffers from security and might expose you to XSS attacks
To prevent XSS attacks, You should sanitize user input before storing it.
Test
`js
$ npm run test
``