Skip to content

dev-javascript/string-to-react-component

Repository files navigation

string-to-react-component

Create React component from string

Support react >= v16.8.0

Table of Contents

Installation

$ npm install string-to-react-component --save

Also You need to load @babel/standalone in the browser :

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Basic Example

import StringToReactComponent from 'string-to-react-component';
function App() {
  return (
    <StringToReactComponent>
      {`(props)=>{
         const {useState}=React;
         const [counter,setCounter]=useState(0);
         const increase=()=>{
           setCounter(counter+1);
         };
         return (<>
           <button onClick={increase}>+</button>
           <span>{'counter : '+ counter}</span>
           </>);
       }`}
    </StringToReactComponent>
  );
}

Notes

  • The given code inside the string should be a function.

  • The given code is executed in the global scope, so imported objects from react package including useState, useEffect, ... are not accessible inside it and you should get them from React global variable :

import {useState} from 'react';
import StringToReactComponent from 'string-to-react-component';
function App() {
  return (
    <StringToReactComponent>
      {`()=>{
         console.log(typeof useState); // undefined
         console.log(typeof React.useState); // function

         ...

       }`}
    </StringToReactComponent>
  );
}

Using Unknown Elements

import StringToReactComponent from 'string-to-react-component';
import MyComponent from 'path to MyComponent';
function App() {
  return (
    <StringToReactComponent MyComponent={MyComponent}>
      {`(props)=>{
         const {MyComponent}=props;
         return (<MyComponent/>);
       }`}
    </StringToReactComponent>
  );
}

Test

$ npm run test

License

MIT