react-json-reconciler
TypeScript icon, indicating that this package has built-in type declarations

3.0.1 • Public • Published

react-json-reconciler

This project leverages the react-reconciler to allow users to serialize JSX trees into JSON objects.



Install

yarn add react-json-reconciler
npm i --save react-json-reconciler

Usage

There are 4 primitive JSX elements, that can be used to construct a normal JSX tree. All the things you'd expect to have access to in React (state, hooks props) all work as they normally would. To serialize the elements into JSON, call render and await the response. This will wait for all useEffect and setState updates to settle before returning the result.

import React from "react";
import { render } from "react-json-reconciler";

const element = (
  <obj>
    <property key="Prop 1">
      <array>
        <value>Value 1</value>
      </array>
    </property>
    <property key="Prop 2">Value 2</property>
  </obj>
);

const { jsonValue } = await render(element);

The above will generate

{
  "Prop 1": ["Value 1"],
  "Prop 2": "Value 2"
}

Source Maps

In order to generate source-map support, React must be in development mode (process.env.NODE_ENV != 'production'), and the @babel/plugin-transform-react-jsx-source plugin enabled (included as part of @babel/preset-react)

Pass the collectSourceMap: true option to the render method.

Refs

For each of the primitive types, any ref will return a respective JSON AST node. This allows users to introspect and manipulate the tree before rendering when coupled with a useEffect() or useLayoutEffect().

Example:

import React from "react";

const CustomComponent = (props) => {
  const objRef = React.useRef(null);

  React.useEffect(() => {
    // A chance to introspect the JSON AST node before being serialized
  }, [objRef]);

  return <obj ref={objRef}>{props.children}</obj>;
};

License

react-json-reconciler is provided under the MIT license.

Contributors ✨

Feel free to open an issue or a pull request!

Make sure to read our code of conduct.

We actively welcome pull requests. Learn how to contribute.

Thanks goes to these wonderful people (emoji key):


Adam Dierkens

💻 📖 💡 🚇 🚧 📦 ⚠️ 🔧

Clifford Fajardo

🚇

This project follows the all-contributors specification. Contributions of any kind welcome!

Readme

Keywords

none

Package Sidebar

Install

npm i react-json-reconciler

Weekly Downloads

134

Version

3.0.1

License

MIT

Unpacked Size

136 kB

Total Files

22

Last publish

Collaborators

  • adierkens