json-react

1.0.0 • Public • Published

json-react

Convert objects to React elements and elements to serializable objects

npm i json-react

Convert React element to object

import jsonReact from 'json-react'
 
const el = (
  <div>
    <h1>Hello</h1>
  </div>
)
 
const obj = jsonReact.toObject(el)
// returns
{
  type: 'div',
  props: null,
  children: [
    {
      type: 'h1',
      props: null,
      children: [
        'Hello'
      ]
    }
  ]
}

Convert object to React element

import jsonReact from 'json-react'
 
const el = jsonReact.toElement({
  type: 'div',
  props: null,
  children: [
    {
      type: 'h1',
      props: null,
      children: [
        'Hello'
      ]
    }
  ]
})
// returns
<div>
  <h1>Hello</h1>
</div>

Convert object to React element with references to components

import jsonReact from 'json-react'
import MyComponent from './MyComponent'
 
const el = jsonReact.toElement({
  type: 'MyComponent',
  props: {},
  children: [
    'Hello'
  ]
}, { MyComponent })
 
// <MyComponent>Hello</MyComponent>

Why?

  • Demonstrate how React elements are objects and can be converted to and from JSON
  • Components can be serialized by displayName
  • Components can be passed as scope to create elements from objects

Readme

Keywords

none

Package Sidebar

Install

npm i json-react

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

12.5 kB

Total Files

7

Last publish

Collaborators

  • jxnblk