### Complete DataFetcher Setup Example Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/DataFetcher-class.md Demonstrates how to initialize DataFetcher, register page, layout, and common processors, and then process a page with extra data. ```typescript import {DataFetcher} from '/lib/enonic/react4xp/DataFetcher';\n\nconst dataFetcher = new DataFetcher();\n\n// Register page processor\ndataFetcher.addPage('myapp:article', {\n processor: ({content, request}) => {\n return {\n title: content.displayName,\n published: content.publish?.from,\n author: content.data.author\n };\n }\n});\n\n// Register layout processor\ndataFetcher.addLayout('myapp:main-layout', {\n processor: ({component}) => {\n return {\n layoutClass: component.config?.cssClass || 'layout-default'\n };\n }\n});\n\n// Register common processor (runs for all content)\ndataFetcher.addCommon({\n processor: ({content}) => {\n return {\n contentId: content._id,\n contentPath: content._path\n };\n }\n});\n\n// Process a page\nconst result = dataFetcher.process({\n request,\n extraData: {version: '1.0'}\n});\n\nlog.info('Processed: ' + JSON.stringify(result)); ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Installs necessary Babel and Webpack packages as development dependencies. ```commandline npm add --save-dev @babel/cli@7 @babel/core@7 @babel/preset-env@7 @babel/preset-react@7 @babel/register@7 webpack@4 webpack-cli@3 ``` -------------------------------- ### Include React4xp Gradle Build Setup Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Applies the shared react4xp.gradle build script from the NPM package. Ensure npm install has been run prior to the Gradle build. ```groovy apply from: "node_modules/react4xp/react4xp.gradle" ``` -------------------------------- ### Application Configuration Example Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Shows a sample `xp.json` configuration snippet for `react4xp`, including settings for hydration, SSR, and URL type. ```json { "config": { "react4xp": { "hydrate": "true", "ssr": "true", "ssr.maxThreads": 4, "urlType": "server" } } } ``` -------------------------------- ### Example xp.json Configuration Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/configuration.md Illustrates how to set lib-react4xp configuration options within the application's xp.json file. ```json { "app": { "name": "com.example.myapp", "version": "1.0.0" }, "config": { "react4xp": { "hydrate": "true", "ssr": "true", "urlType": "server" } } } ``` -------------------------------- ### Example Render Options Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/configuration.md Demonstrates how to use render options to configure a React4xp.render call, overriding application settings. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const response = React4xp.render( 'site/parts/SearchResults/SearchResults', {query: 'react'}, request, { ssr: true, hydrate: true, id: 'search-results', pageContributions: { headEnd: [''] }, urlType: 'absolute' } ); ``` -------------------------------- ### Install NPM Packages for React4xp Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Install the necessary NPM packages as devDependencies in your parent XP project folder. Ensure the NPM package version matches the library version. ```commandline npm install --save-dev @enonic/react4xp ``` -------------------------------- ### Render Component with Options Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md A concise example showing the signature for the `render` function, including the entry point, props, request object, and rendering options. ```typescript const response = render(entry, props, request, options); ``` -------------------------------- ### Data Fetching Setup and Processing Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/OVERVIEW.md Demonstrates setting up a DataFetcher to process content of a specific type and then processing a request. This is useful for fetching and transforming data for components. ```typescript import {DataFetcher} from '/lib/enonic/react4xp'; const dataFetcher = new DataFetcher(); // Register processors dataFetcher.addPage('myapp:article', { processor: ({content}) => ({ title: content.displayName, body: content.data.body }) }); // Process content const result = dataFetcher.process({request}); // Returns: {component, data, common, meta} ``` -------------------------------- ### Example Usage of EntryName Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/types.md Demonstrates how to declare an EntryName variable with a typical component path. ```typescript const entryName: EntryName = 'site/parts/SearchResults/SearchResults'; ``` -------------------------------- ### Example: Accessing App Configuration Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/types.md Demonstrates how to access and use the AppConfig interface in TypeScript code after casting the application configuration. Shows how to check if SSR is enabled. ```typescript // In xp.json { "react4xp": { "hydrate": "true", "ssr": "true", "urlType": "server" } } // Access in code const config = app.config as AppConfig; const ssrEnabled = config['react4xp.ssr'] !== 'false'; ``` -------------------------------- ### Install lib-react4xp TS Types Source: https://github.com/enonic/lib-react4xp/blob/master/types/README.md Install the @enonic-types/lib-react4xp package as a development dependency using npm. ```bash npm i --save-dev @enonic-types/lib-react4xp ``` -------------------------------- ### Configure Component Props Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Example of how to set props for a React4xp component instance using the `setProps` method. ```typescript r4x.setProps({title: 'Hello'}); ``` -------------------------------- ### Example: Using OneOrMore Type Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/types.md Illustrates the usage of the OneOrMore utility type, showing how a variable can be assigned either a single string or an array of strings. ```typescript type Entries = OneOrMore; // Accepts either a string or string[] const single: Entries = 'site/parts/Header/Header'; const multiple: Entries = ['site/parts/Header/Header', 'site/parts/Footer/Footer']; ``` -------------------------------- ### Register Component Processors Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Example of registering a custom processor for a specific component type using `DataFetcher.addPage`. ```typescript dataFetcher.addPage('myapp:article', { processor: ({content, request}) => ({...}) }); ``` -------------------------------- ### React4xp.getClientUrl Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/utility-functions.md Gets the URL to the React4xp client wrapper bundle, which is necessary for client-side rendering. ```APIDOC ## React4xp.getClientUrl ### Description Gets the URL to the React4xp client wrapper bundle. ### Method `React4xp.getClientUrl(params?: { urlType?: UrlType }): string` ### Parameters #### Query Parameters - **urlType** (UrlType) - Optional - Specifies the type of URL to retrieve (e.g., 'path', 'absolute'). Defaults to 'path'. ### Request Example ```typescript import { React4xp } from '/lib/enonic/react4xp'; const clientUrl = React4xp.getClientUrl({ type: 'absolute' }); ``` ``` -------------------------------- ### Configure XP Component Transpilation Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Example Gradle task to compile XP components using Babel, specifically ignoring JSX files to prevent conflicts with React4xp's own compilation. This task is added to the main jar dependency. ```groovy task compileXP(type: NodeTask) { description 'Compile regular (non-React4xp) XP components from ES6, ignoring JSX components' script = file('node_modules/@babel/cli/bin/babel.js') args = ["src/main/resources", "--out-dir", "build/resources/main", "--ignore", "**/*.jsx"] // <-- Ignoring JSX in the XP structure inputs.dir 'src/main/resources' outputs.dir("build/resources/main") } jar.dependsOn += 'compileXP' ``` -------------------------------- ### Basic Component Rendering in Part Controller Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Demonstrates how to use the `render` function within an Enonic XP part controller's `get` method to render a React component. It includes basic props and SSR/hydration options. ```typescript // Render a component in a part controller exports.get = function(req) { return render( 'site/parts/MyPart/MyPart', {title: 'Hello World'}, req, {ssr: true, hydrate: true} ); }; ``` -------------------------------- ### Render React Component (Page) Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md This example shows how to render a React page component in its controller. It automatically derives component details from the XP content and passes content-specific props. ```typescript import {render} from '/lib/enonic/react4xp'; import {getContent} from '/lib/xp/portal'; exports.get = (req) => { const content = getContent(); return render( // Can pass the page component object for auto-derivation {type: 'page', descriptor: 'myapp:article', ...content.page}, { title: content.displayName, body: content.data.body, author: content.data.author }, req // Options are optional; uses app.config defaults ); }; ``` -------------------------------- ### Configure tsconfig.json for lib-react4xp Types Source: https://github.com/enonic/lib-react4xp/blob/master/types/README.md Add the type definitions for lib-react4xp to your tsconfig.json file to enable server-side TypeScript compilation. This configuration maps the module path to the installed types. ```json { "compilerOptions": { "paths": { "/lib/enonic/react4xp": ["./node_modules/@enonic-types/lib-react4xp"] } } } ``` -------------------------------- ### Build lib-react4xp from Source (Gradle Command) Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Execute the Gradle command to build and publish the library to your local Maven repository. ```commandline gradlew publishToMavenLocal ``` -------------------------------- ### Get React4xp Client URL Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md React4xp.getClientUrl returns the URL for the React4xp client wrapper bundle. You can specify the URL type to get a server-relative, absolute, or relative URL. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const clientUrl = React4xp.getClientUrl(); // → /_/service/com.myapp/asset/r4xAssets/client.abc123.js const absoluteUrl = React4xp.getClientUrl({type: 'absolute'}); // → https://example.com/_/service/com.myapp/asset/r4xAssets/client.abc123.js ``` -------------------------------- ### Get Component Chunk URLs Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md Retrieves the URLs for component chunk files. Use this to get the specific URLs for your React components' JavaScript bundles, which can be used for including them in your HTML. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const urls = React4xp.getComponentChunkUrls({ entries: [ 'site/parts/Header/Header', 'site/parts/Footer/Footer' ] }); // → [ // '/_/service/com.myapp/asset/r4xAssets/site/parts/Header/Header.abc123.js', // '/_/service/com.myapp/asset/r4xAssets/site/parts/Footer/Footer.def456.js' // ] // Single entry const singleUrl = React4xp.getComponentChunkUrls({ entries: 'site/parts/Hero/Hero' }); // → ['/_/service/com.myapp/asset/r4xAssets/site/parts/Hero/Hero.xyz789.js'] ``` -------------------------------- ### Initialize React4xp Instance Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/React4xp-class.md Demonstrates different ways to initialize a React4xp instance using a direct JSX path, auto-derivation from context, or by passing a component object. ```typescript import {React4xp} from '/lib/enonic/react4xp/React4xp'; // Direct JSX path initialization const r4x = new React4xp('site/parts/MyPart/MyPart'); // Auto-derive from component context (in a part controller) const r4xAuto = new React4xp(); // Initialize with component object const {getComponent} = require('/lib/xp/portal'); const component = getComponent(); const r4xComponent = new React4xp(component); ``` -------------------------------- ### React4xp Instance - Configuration Methods Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Methods to configure a React4xp instance, supporting chaining. ```APIDOC ## React4xp Instance - Configuration Methods ### `setProps(props)` #### Description Sets the props for the component. #### Parameters - **props** (Props) - The properties to set. #### Returns `this` (for chaining) ### `setId(id)` #### Description Sets the container HTML ID for the component. #### Parameters - **id** (string) - The ID to set. #### Returns `this` (for chaining) ### `setJsxPath(path)` #### Description Sets the path to the JSX file. #### Parameters - **path** (string) - The JSX file path. #### Returns `this` (for chaining) ### `setIsPage(bool)` #### Description Marks the component as a page. #### Parameters - **bool** (boolean) - True if it's a page, false otherwise. #### Returns `this` (for chaining) ### `setHasRegions(bool)` #### Description Indicates if the component has regions. #### Parameters - **bool** (boolean) - True if it has regions, false otherwise. #### Returns `this` (for chaining) ### `uniqueId()` #### Description Generates a unique ID for the component. #### Returns `this` (for chaining) ``` -------------------------------- ### React4xp.getExecutorUrl Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/utility-functions.md Gets the URL to the server-side rendering executor, used for rendering React components on the server. ```APIDOC ## React4xp.getExecutorUrl ### Description Gets the URL to the server-side rendering executor. ### Method `React4xp.getExecutorUrl(params?: { urlType?: UrlType }): string` ### Parameters #### Query Parameters - **urlType** (UrlType) - Optional - Specifies the type of URL to retrieve (e.g., 'path', 'absolute'). Defaults to 'path'. ### Request Example ```typescript import { React4xp } from '/lib/enonic/react4xp'; const executorUrl = React4xp.getExecutorUrl(); ``` ``` -------------------------------- ### Deploy Project Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Deploys the Enonic XP project using the standard command. ```commandline enonic project deploy ``` -------------------------------- ### Build lib-react4xp from Source Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Build the lib-react4xp library locally using Gradle. This involves cloning the source, updating the version in gradle.properties, and publishing to the local Maven repository. ```properties version = 3.1.0 ``` -------------------------------- ### render() Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md The primary entry point for rendering React components. This function wraps the React4xp class and is the recommended way to render components. ```APIDOC ## render() ### Description The `render()` function is the main entry point for rendering React components. It handles the creation of a React4xp instance, configuration with props and options, rendering to HTML (SSR or client-render), and generation of page contributions. ### Parameters #### Parameters - **entry** (`Entry`) - Required - JSX path string or XP component object - **props** (`object`) - Optional - Top-level component props (must be JSON-serializable) - **request** (`Request`) - Optional - Enonic XP request object (from portal context) - **options** (`RenderOptions`) - Optional - Rendering configuration options #### RenderOptions - **body** (`string`) - Optional - Pre-rendered HTML to include in response - **hydrate** (`boolean`) - Optional - Enable client-side hydration (overrides app.config['react4xp.hydrate']) - **id** (`string`) - Optional - Custom HTML ID for the target container - **pageContributions** (`object`) - Optional - Merge with existing XP page contributions - **ssr** (`boolean`) - Optional - Enable server-side rendering (overrides app.config; pages/layouts default to true) - **wrapper** (`boolean`) - Optional - Wrap component HTML in a container div - **urlType** (`UrlType`) - Optional - Asset URL type ('server', 'absolute', 'relative') - **uniqueId** (`boolean | string`) - Optional - Generate unique ID (true) or use provided string ### Returns An Enonic XP Response object containing `body` (rendered HTML) and `pageContributions` (scripts/styles for head and body). ### Throws Does not throw. Catches all errors and returns an error placeholder in the response body. ### Example: Part Rendering ```javascript // In part controller: src/main/resources/site/parts/SearchResults/SearchResults.js import {render} from '/lib/enonic/react4xp'; exports.get = (req) => { const query = req.params.q || ''; return render( 'site/parts/SearchResults/SearchResults', {query, limit: 20}, req, { ssr: true, hydrate: true, id: 'search-results-root' } ); }; ``` ### Example: Page Rendering ```javascript // In page controller: src/main/resources/site/pages/Article/Article.js import {render} from '/lib/enonic/react4xp'; import {getContent} from '/lib/xp/portal'; exports.get = (req) => { const content = getContent(); return render( // Can pass the page component object for auto-derivation {type: 'page', descriptor: 'myapp:article', ...content.page}, { title: content.displayName, body: content.data.body, author: content.data.author }, req // Options are optional; uses app.config defaults ); }; ``` ### Example: Layout Rendering ```javascript // In layout controller: src/main/resources/site/layouts/TwoColumn/TwoColumn.js import {render} from '/lib/enonic/react4xp'; exports.get = (req) => { return render( // Auto-derive from portal context (component + content available) null, {columnWidths: [60, 40]}, req ); }; ``` ``` -------------------------------- ### Get React4xp Executor URL Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md React4xp.getExecutorUrl returns the URL for the server-side rendering executor bundle. Similar to getClientUrl, you can specify the URL type. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const executorUrl = React4xp.getExecutorUrl(); // → /_/service/com.myapp/asset/r4xAssets/executor.abc123.js ``` -------------------------------- ### Builder Pattern Rebuilding from Parameters Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/advanced-patterns.md Shows how to create a configured React4xp instance using the static `_buildFromParams` method. Useful for recreating configurations from stored parameters. ```typescript const r4x = React4xp._buildFromParams({ entry: 'site/parts/MyPart/MyPart', props: {title: 'Hello'}, id: 'my-id', uniqueId: true // or a custom string }); ``` -------------------------------- ### React4xp Instance - Utility Methods Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Utility methods available on React4xp instances. ```APIDOC ## React4xp Instance - Utility Methods ### `makeErrorMessage(attribute)` #### Description Creates a formatted error message. #### Parameters - **attribute** (string) - The attribute for which to create an error message. #### Returns string (formatted error message) ``` -------------------------------- ### React4xp Instance - Rendering Methods Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Methods for rendering component HTML and related assets. ```APIDOC ## React4xp Instance - Rendering Methods ### `renderBody(params?)` #### Description Renders the main component HTML. #### Parameters - **params** ({body?, ssr?, wrapper?, request?}) - Optional parameters for rendering. #### Returns string (rendered HTML) ### `renderPageContributions(params?)` #### Description Generates JavaScript and CSS contributions for the page. #### Parameters - **params** ({hydrate?, pageContributions?, request?, ssr?, urlType?}) - Optional parameters for contributions. #### Returns PageContributions ### `doRenderSSR(overrideProps?)` #### Description Performs Server-Side Rendering (SSR) of the component. #### Parameters - **overrideProps** (Props?) - Optional props to override during SSR. #### Returns {html?, error?} ### `renderSSRIntoContainer(params)` #### Description Renders SSR output into a specified container. #### Parameters - **params** ({body, request, wrapper?}) - Parameters including body, request, and optional wrapper. #### Returns string (rendered HTML) ### `RenderTargetContainer(params)` #### Description Creates a container for rendering content. #### Parameters - **params** ({body?, content?, wrapper?, appendErrorContainer?}) - Parameters for container creation. #### Returns string (container HTML) ### `renderWarningPlaceholder()` #### Description Renders a placeholder warning, typically used in edit mode. #### Returns string (placeholder HTML) ``` -------------------------------- ### Method Chaining for Component Initialization Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Demonstrates extensive method chaining with React4xp to configure a component. This includes setting props, ID, region status, and generating a unique ID. ```typescript const r4x = new React4xp('site/parts/Form/Form') .setProps({ fields: [...], onSubmit: 'handleSubmit' }) .setId('contact-form') .setHasRegions(false) .uniqueId(); const response = { body: r4x.renderBody({request, ssr: true}), pageContributions: r4x.renderPageContributions({hydrate: true}) }; ``` -------------------------------- ### Tune SSR Thread Pool for High Concurrency Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/configuration.md Increase the 'react4xp.ssr.maxThreads' setting in the configuration for scenarios requiring higher concurrency. This example sets the maximum threads to 8. ```json { "react4xp": { "ssr": "true", "ssr.maxThreads": 8 } } ``` -------------------------------- ### Using Static Methods of React4xp Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Shows how to use static methods directly from the React4xp class or via top-level re-exports. This provides access to utility functions like rendering and URL generation. ```typescript // All static on React4xp class React4xp.render(...) React4xp.getClientUrl(...) React4xp.getExecutorUrl(...) React4xp.getComponentChunkUrls(...) // Or re-exported at top level import {render, getClientUrl, ...} from '/lib/enonic/react4xp'; ``` -------------------------------- ### Render React Component (Layout) Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md Use this snippet in a layout controller to render a React layout component. It can auto-derive component details from the portal context, simplifying setup. ```typescript import {render} from '/lib/enonic/react4xp'; exports.get = (req) => { return render( // Auto-derive from portal context (component + content available) null, {columnWidths: [60, 40]}, req ); }; ``` -------------------------------- ### React4xp Class - Constructor & Statics Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Details on the React4xp class constructor and static methods. ```APIDOC ## React4xp Class - Constructor & Statics ### `new React4xp(entry)` #### Description Constructor for the React4xp class. #### Parameters - **entry** (Entry) - The entry point for the React4xp application. #### Returns React4xp instance ### `React4xp.render()` #### Description Static method to render React4xp components. #### Signature `static render(entry, props?, request?, options?)` ### `React4xp.getClientUrl()` #### Description Static getter for the client wrapper URL. #### Signature `static getClientUrl(params?)` ### `React4xp.getExecutorUrl()` #### Description Static getter for the SSR executor URL. #### Signature `static getExecutorUrl(params?)` ### `React4xp.getComponentChunkUrls()` #### Description Static getter for component chunk URLs. #### Signature `static getComponentChunkUrls(params)` ``` -------------------------------- ### Build Project Locally Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Executes the Gradle build for the project locally. ```commandline gradlew build ``` -------------------------------- ### Project File Organization Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/MANIFEST.md Shows the directory structure of the lib-react4xp project, indicating the purpose of each file. ```text /workspace/home/output/ ├── README.md (Primary index) ├── OVERVIEW.md (Architecture) ├── MANIFEST.md (This file) ├── configuration.md (App config) ├── types.md (Type definitions) ├── advanced-patterns.md (Advanced usage) └── api-reference/ ├── QUICK-REFERENCE.md (Fast lookup) ├── React4xp-class.md (Main class) ├── DataFetcher-class.md (Content processor) ├── exported-functions.md (Top-level functions) └── utility-functions.md (Utility functions) ``` -------------------------------- ### React4xp Constructor Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/React4xp-class.md Initializes a React4xp instance. It can accept an explicit JSX path, an XP component object, or auto-derive the entry from the current context if no value is provided. ```APIDOC ## Constructor React4xp ### Description Initializes a React4xp instance with a given entry point. The constructor: 1. Accepts a JSX path string for explicit path specification, or 2. Accepts an XP component/page object for component-based rendering, or 3. Auto-derives the entry from portal context (component or page) if entry is falsy When auto-deriving, it extracts component metadata (descriptor, type, path) and constructs an appropriate jsxPath and react4xpId. ### Parameters - **entry** (`Entry` (string | Component)) - Required - Either a JSX path string (e.g., `'site/parts/MyPart/MyPart'`) or an XP component object (portal.getComponent() or portal.getContent().page). If falsy, the constructor attempts to auto-derive the entry from the current context. ### Throws - **Error** if entry is invalid (not a string, component object, or falsy value in appropriate context) - **Error** if component derivation fails (missing descriptor, type, or path) - **Error** if entry string is empty ### Example ```typescript import {React4xp} from '/lib/enonic/react4xp/React4xp'; // Direct JSX path initialization const r4x = new React4xp('site/parts/MyPart/MyPart'); // Auto-derive from component context (in a part controller) const r4xAuto = new React4xp(); // Initialize with component object const {getComponent} = require('/lib/xp/portal'); const component = getComponent(); const r4xComponent = new React4xp(component); ``` ``` -------------------------------- ### Instantiate DataFetcher Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/DataFetcher-class.md Creates an empty DataFetcher instance. This is the first step before registering any processors. ```typescript import {DataFetcher} from '/lib/enonic/react4xp/DataFetcher'; const dataFetcher = new DataFetcher(); ``` -------------------------------- ### Add lib-react4xp from Repository Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Include lib-react4xp as a dependency in your parent project's build.gradle file. Ensure the Enonic public repository is configured. ```groovy dependencies { include 'com.enonic.lib:lib-react4xp:3.1.0' } repositories { maven { url 'http://repo.enonic.com/public' } } ``` -------------------------------- ### Process Content and Extract Data Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Shows how to use the `DataFetcher` class's `process` method to handle XP content and extract necessary data for rendering. ```typescript const result = dataFetcher.process({request, content, component}); ``` -------------------------------- ### DataFetcher Execution Flow Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Outlines the steps involved in the DataFetcher's process, from receiving input to returning a ProcessResult. ```mermaid process({request, content, component}) ↓ Check content type ↓ Route to processor ↓ Invoke processor ↓ Process regions (recursive) ↓ Invoke common processor ↓ Return ProcessResult ``` -------------------------------- ### Link Local NPM Packages Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Runs the npmLink Gradle task from the react4xp-npm project to set up local symlinks for development. ```commandline gradlew npmLink ``` -------------------------------- ### React4xp.render() Static Method Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/React4xp-class.md A static convenience method to render React components. It creates a React4xp instance, configures it, and handles the rendering process, including SSR and error management. ```APIDOC ## Static Method: React4xp.render() ### Description Static convenience method that creates a React4xp instance, configures it with provided options, and renders it. This is the primary entry point for most use cases. The method automatically handles SSR defaults (pages and layouts default to SSR=true), deep-clones options to prevent mutations, and gracefully handles rendering errors. ### Parameters - **entry** (`Entry`) - Required - JSX path string or XP component object - **props** (`object`) - Optional - Top-level props to pass to the React component. Must be JSON-serializable. - **request** (`Request`) - Optional - The current HTTP request object from Enonic XP - **options** (`RenderOptions`) - Optional - Rendering configuration options ### RenderOptions - **body** (`string`) - Pre-rendered HTML body to include in the response - **hydrate** (`boolean`) - Enable client-side hydration (overrides app.config) - **id** (`Id`) - Custom HTML ID for the target container - **pageContributions** (`PageContributions`) - Existing XP page contributions to merge with generated ones - **ssr** (`boolean`) - Enable server-side rendering (overrides app.config; defaults true for pages/layouts) - **wrapper** (`boolean`) - Wrap component HTML in a container element - **urlType** (`UrlType`) - Asset URL type ('server', 'absolute', 'relative') - **uniqueId** (`boolean | string`) - Auto-generate or set a unique ID for the container ### Returns An Enonic XP `Response` object with: - `body`: Rendered HTML markup - `pageContributions`: JavaScript/CSS dependencies and hydration scripts ### Throws No explicit throws, but catches and logs all errors, returning an error placeholder container in the response. ### Example ```typescript import {render} from '/lib/enonic/react4xp/React4xp'; import {getComponent} from '/lib/xp/portal'; const component = getComponent(); const response = render(component, {title: 'Hello World'}, request, { ssr: true, hydrate: true, id: 'my-component' } ); ``` ``` -------------------------------- ### Export Summary for React4xp Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md This code block shows the main exports from the React4xp library's entry point. It includes core components and utility functions. ```typescript export { React4xp, getClientUrl, getComponentChunkUrls, getExecutorUrl, render } from '/lib/enonic/react4xp/React4xp'; export {assetUrl} from '/lib/enonic/react4xp/assetUrl'; export {DataFetcher} from '/lib/enonic/react4xp/DataFetcher'; export {serviceUrl} from '/lib/enonic/react4xp/serviceUrl'; export {processHtml} from '/lib/enonic/react4xp/dataFetcher/processHtml'; ``` -------------------------------- ### AppConfig Interface Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/configuration.md Defines the structure for application-level configuration of lib-react4xp within xp.json. ```typescript interface AppConfig { 'react4xp.hydrate'?: 'true' | 'false'; 'react4xp.ssr'?: 'true' | 'false'; 'react4xp.ssr.maxThreads'?: number | string | unknown; 'react4xp.urlType'?: UrlType; } ``` -------------------------------- ### Entry Type Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/types.md Defines a React4xp entry point, which can be either a string representing an absolute JSX path or an Enonic XP Component object. ```APIDOC ## Entry Type ### Description A React4xp entry point, either a JSX path string or an Enonic XP Component object. ### Type Definition ```typescript type Entry = string | Component ``` ### Type Details - **string**: Absolute JSX path (e.g., `'site/parts/MyPart/MyPart'`) - **Component**: XP component object from portal.getComponent() or similar ### Used By React4xp constructor, React4xp.render() ``` -------------------------------- ### React4xp Render Flow Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Illustrates the sequence of operations during the React4xp render process, from entry point to response. ```mermaid render(entry, props, request, options) ↓ Create React4xp(entry) ↓ Configure (props, id, etc) ↓ renderBody(options) ↓ renderPageContributions(options) ↓ Return Response ``` -------------------------------- ### Import Core React4xp Modules Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/README.md Import all essential modules from the lib-react4xp library. This includes the main React4xp class and various utility functions for rendering and URL generation. ```typescript import { React4xp, render, DataFetcher, assetUrl, serviceUrl, processHtml, getClientUrl, getExecutorUrl, getComponentChunkUrls } from '/lib/enonic/react4xp'; ``` -------------------------------- ### DataFetcher Constructor Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/DataFetcher-class.md Creates an empty DataFetcher instance. No parameters are required. This instance is ready to have processor functions registered for different content types. ```APIDOC ## DataFetcher Constructor ### Description Creates an empty DataFetcher instance. This instance is ready to register processor functions for various XP content types. ### Parameters None ### Example ```typescript import { DataFetcher } from '/lib/enonic/react4xp/DataFetcher'; const dataFetcher = new DataFetcher(); ``` ``` -------------------------------- ### Usage Import for React4xp Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/exported-functions.md Demonstrates how to import all exported functions and components from the React4xp library into your project. This is typically used at the top of your main application files. ```typescript import { React4xp, render, assetUrl, serviceUrl, getClientUrl, getExecutorUrl, getComponentChunkUrls, DataFetcher, processHtml } from '/lib/enonic/react4xp'; ``` -------------------------------- ### Generate React4xp Client and Executor URLs Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/utility-functions.md These static methods retrieve URLs for essential React4xp client-side assets, such as the client wrapper bundle and the server-side rendering executor. They are useful for setting up the necessary scripts and endpoints for React4xp applications. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const clientUrl = React4xp.getClientUrl({type: 'absolute'}); const executorUrl = React4xp.getExecutorUrl(); const componentUrls = React4xp.getComponentChunkUrls({ entries: ['site/parts/Header/Header', 'site/parts/Footer/Footer'] }); ``` -------------------------------- ### Builder Pattern Chaining Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/advanced-patterns.md Demonstrates chaining methods on the React4xp builder for fluent configuration. Ensure React4xp is imported. ```typescript import {React4xp} from '/lib/enonic/react4xp'; const r4x = new React4xp('site/parts/Product/Product'); r4x .setProps({productId: 123}) .setId('product-viewer') .setHasRegions(true) .setIsPage(false); const body = r4x.renderBody({ssr: true}); const contributions = r4x.renderPageContributions({hydrate: true}); ``` -------------------------------- ### Accessing and Overriding Configuration in Code Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/configuration.md Shows how to read application configuration and override settings during a React4xp.render call. ```typescript import {React4xp} from '/lib/enonic/react4xp'; import type {AppConfig} from '/lib/enonic/react4xp'; // Read configuration const appConfig = app.config as AppConfig; const isHydrationEnabled = appConfig['react4xp.hydrate'] !== 'false'; const isSsrEnabled = appConfig['react4xp.ssr'] !== 'false'; const maxThreads = appConfig['react4xp.ssr.maxThreads']; const urlType = appConfig['react4xp.urlType'] || 'server'; // Override in render call const response = React4xp.render(entry, props, request, { hydrate: true, // Overrides app.config['react4xp.hydrate'] ssr: true, // Overrides app.config['react4xp.ssr'] urlType: 'absolute' }); ``` -------------------------------- ### Static React4xp.render() Method Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/React4xp-class.md A static convenience method to render a React component, handling instance creation, configuration, and SSR defaults. It accepts the entry point, optional props, request object, and rendering options. ```typescript import {render} from '/lib/enonic/react4xp/React4xp'; import {getComponent} from '/lib/xp/portal'; const component = getComponent(); const response = render(component, {title: 'Hello World'}, request, { ssr: true, hydrate: true, id: 'my-component' } ); ``` -------------------------------- ### React4xp Instance - ID Management Methods Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Methods for managing component IDs, including locking. ```APIDOC ## React4xp Instance - ID Management Methods ### `checkIdLock()` #### Description Verifies if the component's ID is currently locked. #### Effect Throws an error if the ID is locked. ### `ensureAndLockId()` #### Description Ensures an ID exists and locks it. Generates an ID if it's missing. ### `ensureAndLockBeforeRendering()` #### Description Ensures and locks the ID before rendering commences. #### Effect Called automatically during the rendering process. ``` -------------------------------- ### DataFetcher Class - Registration Methods Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Methods for registering processors for different content types within DataFetcher. ```APIDOC ## DataFetcher Class - Registration Methods ### `addPage(descriptor, {processor})` #### Description Registers a processor for a specific page descriptor. #### Parameters - **descriptor** (PageDescriptor) - The descriptor for the page. - **processor** (ComponentProcessor) - The processor function. #### Returns void ### `addLayout(descriptor, {processor})` #### Description Registers a processor for a specific layout descriptor. #### Parameters - **descriptor** (LayoutDescriptor) - The descriptor for the layout. - **processor** (ComponentProcessor) - The processor function. #### Returns void ### `addPart(descriptor, {processor})` #### Description Registers a processor for a specific part descriptor. #### Parameters - **descriptor** (PartDescriptor) - The descriptor for the part. - **processor** (ComponentProcessor) - The processor function. #### Returns void ### `addMacro(descriptor, {processor})` #### Description Registers a processor for a specific macro descriptor. #### Parameters - **descriptor** (string) - The descriptor for the macro. - **processor** (ComponentProcessor) - The processor function. #### Returns void ### `addContentType(name, {processor})` #### Description Registers a processor for a specific content type. #### Parameters - **name** (string) - The name of the content type. - **processor** (ComponentProcessor) - The processor function. #### Returns void ### `addCommon({processor})` #### Description Registers a common processor for general use. #### Parameters - **processor** (ComponentProcessor) - The processor function. #### Returns void ``` -------------------------------- ### Instance Interface Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/types.md The type signature for a React4xp instance, detailing all public properties and methods available for managing React components within Enonic XP. ```APIDOC ## Instance Interface ### Description Type signature for a React4xp instance. Documents all public properties and methods. ### Type Definition ```typescript interface Instance { // Public fields assetPath: string; component: Component; hasRegions: 0 | 1; jsxPath: string; isPage: 0 | 1; props: Props; react4xpId: Id; react4xpIdIsLocked: boolean; // Public methods checkIdLock(): void; ensureAndLockId(): void; ensureAndLockBeforeRendering(): void; doRenderSSR(overrideProps?: Props): {error?: string, html?: string}; makeErrorMessage(attribute: string): string; renderBody(params?: {body?: string, request?: Request, wrapper?: boolean, ssr?: boolean}): string; renderPageContributions(params?: {hydrate?: boolean, pageContributions?: PageContributions, request?: Request, ssr?: boolean, urlType?: UrlType}): unknown; renderSSRIntoContainer(params: {body: string, request: Request}): string; renderTargetContainer(params: {appendErrorContainer: boolean, body: string, content: string}): string; renderWarningPlaceholder(): string; setHasRegions(hasRegions: boolean): Instance; setId(id: Id): Instance; setIsPage(isPage: boolean): Instance; setJsxPath(jsxPath: string): Instance; setProps(props: Props): Instance; uniqueId(): Instance; } ``` ### Field Descriptions | Field | Type | Description | |---|---|---| | assetPath | string | Compiled asset path with hash (e.g., 'site/parts/MyPart/MyPart.abc123.js') | | component | Component | XP component object (from portal.getComponent() or similar) | | hasRegions | 0 | 1 | Flag: 1 if component has regions, 0 otherwise | | jsxPath | string | React component path (e.g., 'site/parts/MyPart/MyPart') | | isPage | 0 | 1 | Flag: 1 if entry is a page, 0 otherwise | | props | Props | Top-level props for the React component | | react4xpId | Id | HTML ID for the target container element | | react4xpIdIsLocked | boolean | True if react4xpId is locked from further changes | ### Method Descriptions | Method | Description | |---|---| | checkIdLock() | Checks if the component ID is locked. | | ensureAndLockId() | Ensures and locks the component ID. | | ensureAndLockBeforeRendering() | Ensures and locks the ID before rendering. | | doRenderSSR(overrideProps?: Props) | Renders the component using Server-Side Rendering (SSR), optionally overriding props. Returns an object with potential error or HTML output. | | makeErrorMessage(attribute: string) | Generates an error message for a given attribute. | | renderBody(params?: {body?: string, request?: Request, wrapper?: boolean, ssr?: boolean}) | Renders the component body, with options for wrapping and SSR. | | renderPageContributions(params?: {hydrate?: boolean, pageContributions?: PageContributions, request?: Request, ssr?: boolean, urlType?: UrlType}) | Renders page contributions, with options for hydration, SSR, and URL type. | | renderSSRIntoContainer(params: {body: string, request: Request}) | Renders SSR output directly into a container. | | renderTargetContainer(params: {appendErrorContainer: boolean, body: string, content: string}) | Renders the target container for the component, with options for appending an error container. | | renderWarningPlaceholder() | Renders a placeholder for warnings. | | setHasRegions(hasRegions: boolean) | Sets the hasRegions flag for the instance. Returns the instance. | | setId(id: Id) | Sets the HTML ID for the target container. Returns the instance. | | setIsPage(isPage: boolean) | Sets the isPage flag for the instance. Returns the instance. | | setJsxPath(jsxPath: string) | Sets the JSX path for the instance. Returns the instance. | | setProps(props: Props) | Sets the top-level props for the React component. Returns the instance. | | uniqueId() | Generates and sets a unique ID for the instance. Returns the instance. | ``` -------------------------------- ### Basic Part Rendering with SSR and Hydration Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/OVERVIEW.md Renders a React part on the server and enables client-side hydration. Ensure the JSX path and props are correctly specified. ```typescript import {render} from '/lib/enonic/react4xp'; exports.get = function(req) { return render( 'site/parts/MyPart/MyPart', // JSX path {title: 'Hello'}, req, // Request {ssr: true, hydrate: true} // Options ); }; ``` -------------------------------- ### Preload Assets for Faster Loading Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/advanced-patterns.md Add preload hints to the head of the HTML document to inform the browser about upcoming assets. This improves perceived performance by fetching critical resources early. ```typescript const r4x = new React4xp('site/parts/Heavy/Heavy'); const contributions = r4x.renderPageContributions({ request: req, hydrate: true }); // Add preload hints contributions.headEnd = contributions.headEnd || []; contributions.headEnd.push(` `); return { body: r4x.renderBody({request: req}), pageContributions: contributions }; ``` -------------------------------- ### React4xp Instance Properties Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Lists the properties available on a React4xp instance. These properties define the configuration and state of a React4xp component. ```typescript React4xp ├── assetPath: string ├── component: Component ├── hasRegions: 0|1 ├── isPage: 0|1 ├── jsxPath: string ├── props: Props ├── react4xpId: Id └── react4xpIdIsLocked: boolean ``` -------------------------------- ### Generate Local NPM Links Source: https://github.com/enonic/lib-react4xp/blob/master/README.adoc Executes a shell script to establish necessary symlinks for local NPM package development. Note: This script is not available on Windows. ```commandline sh relative/path/to/local/react4xp-npm/getlinks.sh ``` -------------------------------- ### Simple Component Render Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/api-reference/QUICK-REFERENCE.md Renders a React component. Ensure the component path and props are correctly specified. ```typescript render('site/parts/MyPart/MyPart', {prop: 'value'}, req, {ssr: true}) ``` -------------------------------- ### Two-Step Rendering (Body and Contributions) Source: https://github.com/enonic/lib-react4xp/blob/master/_autodocs/advanced-patterns.md Renders the component body and page contributions separately using `renderBody` and `renderPageContributions`. This allows for more control over the rendering process and is useful when you need to handle these parts independently. ```typescript import {React4xp} from '/lib/enonic/react4xp'; exports.get = function(req) { const r4x = new React4xp('site/parts/MyPart/MyPart'); r4x.setProps({data: 'value'}); // Step 1: Render component body const bodyHtml = r4x.renderBody({ request: req, ssr: true, wrapper: true }); // Step 2: Render page contributions const contributions = r4x.renderPageContributions({ request: req, ssr: true, hydrate: true }); return { body: bodyHtml, pageContributions: contributions }; }; ```