Using React Hooks and extending NetlifyCMS

If you are new to NetlifyCMS and want to discuss or contribute, come join the open source community over in the netlify-cms gitter channel.

I wanted to share. Until v2.9.0 in netlify-cms, you were not able to use hooks in your previews since they were released. A little prodding and poking from yours truly, and some coding with the collaboration of the other maintainers we were able to get this over the finish line.

To be able to use Hooks

You will have to extend netlify-cms using some react project workflow to build your package for an admin page. We will be using codesandbox for this example. It is very easy to extend using create-react-app also.

You will not be using the netlify-cms library package for extending the CMS.
Use netlify-cms-app to extend the CMS from now on.

netlify-cms-app has React (and ReactDOM) as peer dependencies, so you will be making those dependencies in your react project build.

Debug Preview

Our debug preview is going to be 9 lines of actual code (+/- some empty lines). Maybe this is why I pushed so hard to get this implemented. :grinning: Actually there were a ton of reasons for the push for this release.

import React from 'react';

const DebugPreview = ({ entry }) => {
  const [data, setData] = React.useState({});

  React.useEffect(() => {
    setData(entry.toJS());
  }, [entry]);

  return <pre>{JSON.stringify(data, null, 2)}</pre>;
};

export default DebugPreview;

Import the module above into your code and register the widget against one of your collections and edit/create a new item to see the data for an entry.

Being able to use React Hooks has made it really easy to create previews. Here is another example sandbox of some previews in action.

6 Likes