Generating files with the React render engine
The React render engine allows for a more generic way to render multiple files by returning an array of File components in the rendering component. This can be particularly useful for complex templates or when you need to generate a large number of files with varying content.
Example 1: Rendering hardcoded files
The following is a simple hardcoded example of how to render multiple files using the React render engine:
1import { File} from "@asyncapi/generator-react-sdk";
2
3export default function({ asyncapi }) {
4 return [
5 <File name={`file1.html`}>Content</File>,
6 <File name={`file2.html`}>Content</File>
7 ]
8}Example 2: Rendering files based on the AsyncAPI Schema
In practice, to render the multiple files, that are generated from the data defined in your AsyncAPI, you'll iterate over the array of schemas and generate a file for each schema as shown in the example below:
1import { File} from "@asyncapi/generator-react-sdk";
2
3/*
4 * To render multiple files, it is enough to return an array of `File` components in the rendering component, like in following example.
5 */
6export default function({ asyncapi }) {
7 const schemas = asyncapi.allSchemas();
8 const files = [];
9 // schemas is an instance of the Map
10 schemas.forEach((schema) => {
11
12 files.push(
13 // We return a react file component and each time we do it, the name of the generated file will be a schema name
14 // Content of the file will be a variable representing schema
15 <File name={`${schema.id()}.js`}>
16 const { schema.id() } = { JSON.stringify(schema._json, null, 2) }
17 </File>
18 );
19 });
20 return files;
21}Example 3: Rendering files for each channel
Additionally, you can generate multiple files for each channel defined in your AsyncAPI specification using the React render engine as shown in the example below:
1import { File, Text } from "@asyncapi/generator-react-sdk";
2
3
4export default function ({ asyncapi }) {
5 const files = [];
6
7 // Generate files for channels
8 asyncapi.channels().forEach((channel) => {
9 const channelName = channel.id();
10
11 files.push(
12 <File name={`${channelName}.md`}>
13 <Text newLines={2}># Channel: {channelName}</Text>
14 <Text>
15 {channel.hasDescription() && `${channel.description()}`}
16 </Text>
17 </File>
18 );
19 });
20 return files;
21}The code snippet above uses the Text component to write file content to the .md markdown file. The newline property is used to ensure that the content isn't all rendered in one line in the markdown file. In summary, the code snippet above is a practical guide on generating properly formatted multiline Markdown files for each channel in an AsyncAPI document.
You can see an example of a file template that uses the React render engine here.