we're working with Apostrophe CMS v3 and we're trying to add some custom apps to the pages with React. I was able to add components inside using the React CND scripts and loading components as script files in views/layout.html. But it probably isn't best practice. I was wondering if theres a way to add React apps into Apostrophe using npm packages and imports. Thank you very much!
It looks like this question was cross-posted to the Github Discussions forum: https://github.com/apostrophecms/apostrophe/discussions/3393
The response there from the lead software architect:
You can do it in two ways. Which is best depends on your needs.
If you are building a single-page React app but you need some dynamically edited CMS content, you should most likely keep building your React app just as you have been, and use Apostrophe's REST APIs to access piece and page CMS content where you need it. See the documentation on our REST APIs.
On the other hand, if you are building a pretty normal CMS-driven website but you have a few experiences inside your pages that would benefit from embedding a React application, you should carry on with your Nunjucks templates for Apostrophe as you normally would to build a website with Apostrophe, and in addition set up a webpack build of your own to build your React apps, and push the output to a
ui/public/build.js
file nested in any module of your Apostrophe project. Any .js file found in aui/public
subdirectory of a module is automatically included in the frontend bundle generated by Apostrophe.
In that situation, you can still use the REST APIs to access data from the React app, or you can pass data via data attributes in your markup. If you do the latter, the
| jsonAttribute
Nunjucks filter is helpful to turn it into a string that is safe for incorporation into a quoted attribute in your markup.
Hope that helps!