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 React from 'react';
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>
  );
}

Using Unknown Elements

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

Test

$ npm run test

License

MIT