Build a Blog in React with Headless Oracle Content Management
Introduction
React is a JavaScript framework widely used to build web applications. But what happens when you need a content management system (CMS) to serve all of your content? Fortunately, Oracle Content Management, with its rich headless CMS capabilities, has a graceful solution for your content administration and governance needs.
In this tutorial, we’ll build a simple blog in React by leveraging Oracle Content Management as a headless CMS as well as its software development kit (SDK) for content delivery in JavaScript. This React sample is available on GitHub.
The tutorial consists of three steps:
Prerequisites
Before proceeding with this tutorial, we recommend that you read the following information first:
To follow this tutorial, you’ll need:
- an Oracle Content Management subscription
- an Oracle Content Management account with the Content Administrator role
- a Windows or Mac computer with Node version 10 or higher
What We’re Building
Our blog will consist of a three-page site that lets visitors explore blog articles organized into topics. The first page, the home page, will consist of branding (company name and logo), some links, and a list of blog topics.
To take a look at what we’re building, here’s the end state of our tutorial, a basic React blog that consumes content from Oracle Content Management:
https://headless.mycontentdemo.com/samples/oce-react-blog-sample
This is what the home page will look like at the end of this tutorial:
The second page, the topic page, shows previews of each blog article that belongs to the topic. Here’s how an individual topic page will look:
Lastly, the article page renders the final blog article, including information about the blog’s author. Here’s how an individual article page will look:
To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.
Step 1: Prepare Oracle Content Management
If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.
For this tutorial, you’ll need to create a content model in either of two ways. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content, or you can create your own content model and content.
To prepare Oracle Content Management:
- Create a channel and asset repository.
- Create a content model using either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Create a Channel and Asset Repository
You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.
To create a channel and an asset repository in Oracle Content Management:
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.
In the upper right corner, click Create to create a new channel. Name the channel ‘OCEGettingStartedChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.
In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEGettingStartedRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select the OCEGettingStartedChannel channel to indicate to Oracle Content Management that content in the OCEGettingStartedRepository repository can be published to the OCEGettingStartedChannel channel. Click Save when you’re done.
Create a Content Model
The next step is to create a content model. You can use either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Import the Oracle Content Management Samples Asset Pack
You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial. If you prefer, you can also create your own content model rather than download the sample assets pack.
You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. If you want to import the Oracle Content Management Samples Asset Pack, you can download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:
Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEGettingStarted_data.zip.
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEGettingStartedRepository and click the Import Content button in the top action bar.
Upload OCEGettingStarted_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEGettingStarted_data.zip and click OK to import the contents into your asset repository.
After the content has been imported successfully, navigate to the Assets page and open the OCEGettingStartedRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.
Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEGettingStartedChannel.
Before publishing, you need to validate all the assets. First add OCEGettingStartedChannel as a selected channel, and then click the Validate button.
After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.
Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)
After importing the Oracle Content Management Samples Asset Pack, you can start building the blog in React.
Create Your Own Content Model
Instead of importing the Oracle Content Management Samples Asset Pack, you can also create your own content model.
For this tutorial, we’re using a content type called ‘OCEGettingStartedHomePage’ to build the home page for our blog. This home page consists of branding (company name and logo), some URLs for links, and a list of blog topics that should be included on the page.
To create content types for the content model:
- Log in to the Oracle Content Management web interface as an administrator.
- Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
- Click Create in the top right corner.
- Choose to create a content type (not a digital asset type). Repeat this for all required content types.
We’ll create four content types, each with its own set of fields:
- OCEGettingStartedHomePage
- OCEGettingStartedTopic
- OCEGettingStartedAuthor
- OCEGettingStartedArticle
The first content type, OCEGettingStartedHomePage, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Company Name | Single-value text field | X | company_name |
Company Logo | Single-value text field | X | company_logo |
Topics | Multiple-value reference field | X | topics |
Contact URL | Single-value text field | X | contact_url |
About URL | Single-value text field | X | about_url |
This is what your OCEGettingStartedHomePage content type definition should look like:
The second content type, OCEGettingStartedTopic, should have the following field:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Thumbnail | Single-value image field | X | thumbnail |
This is what your OCEGettingStartedTopic content type should look like:
The third content type, OCEGettingStartedAuthor, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Avatar | Single-value image field | X | avatar |
This is what your OCEGettingStartedAuthor content type should look like:
The fourth and final content type, OCEGettingStartedArticle, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
Published Date | Single-value date field | X | published_name |
Author | Single-value reference field | X | author |
Image | Single-value image field | X | image |
Image Caption | Single-value text field | X | image_caption |
Article Content | Single-value large-text field | X | article_content |
Topic | Single-value reference field | X | topic |
This is what your OCEGettingStartedArticle content type should look like:
Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEGettingStartedRepository:
- Log in to the Oracle Content Management web interface as an administrator.
- Navigate to OCEGettingStartedRepository.
- Edit the repository and, under Asset Types, specify all four newly created content types. Click the Save button to save the changes.
After adding the content types to the repository, you can open the OCEGettingStartedRepository repository on the Assets page and start creating your content items for all the content types.
Step 2: Build the Blog in React
To consume our Oracle Content Management content in a server-side rendered React application, we can use the React blog sample, which is available as an open-source repository on GitHub.
Note: Remember that using the React sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own React application.
To build the blog in React:
- Clone the sample repository and install dependencies
- Configure the React application
- Work with the Oracle Content Management Content SDK
- Use the Content SDK to Fetch Content
Clone the Sample Repository and Install Dependencies
The React blog sample is available as an open-source repository on GitHub.
You’ll first need to clone the sample from GitHub to your local computer and change your directory into the repository root:
git clone https://github.com/oracle/oce-react-blog-sample.git
cd oce-react-blog-sample
Now that you have your code base, you need to download dependencies for the application. Run the following command from the root directory:
npm install
Configure the React Application
In this React blog sample, you need to configure a few pieces of information so that your Oracle Content Management Content SDK (and any other requests) can target the correct instance URL and API version with the correct channel token. These values are used in src/scripts/server-config-utils.js to instantiate a new delivery client.
This application uses an .env file that is read by Webpack when it bundles the client and server applications. By using webpack.DefinePlugin, any values read from the .env file can be made available to anywhere in the application.
Open the .env file in a text editor. You’ll see the following information:
# The connection details for the Oracle Content Management server to be used for this application
SERVER_URL=https://samples.mycontentdemo.com
API_VERSION=v1.1
CHANNEL_TOKEN=47c9fb78774d4485bc7090bf7b955632
Change each key-value pair to reflect your instance URL, the API version you want to target, and the channel token associated with your publishing channel. The channel for this tutorial is OCEGettingStartedChannel.
The other setting in the file is the port on which your server application will run. Adjust the setting according to your environment.
# The port the Express Server is to run on
EXPRESS_SERVER_PORT=8080
Work with the Oracle Content Management Content SDK
Oracle Content Management offers an SDK to help discover and use content in your applications. The SDK is published as an NPM module, and the project is hosted on GitHub.
Learn more about the SDK here.
The SDK has been registered as a runtime dependency of this project in the package.json file.
Use the Content SDK to Fetch Content
We can now leverage the Content SDK to fetch content so that we can render it in our React application.
The src/scripts folder contains the code for getting data from Oracle Content Management using the Content SDK.
The src/scripts/server-config-utils.js file imports the Content SDK and then creates a delivery client using the configuration specified in .env.
The following command imports the SDK:
import { createDeliveryClient, createPreviewClient } from '@oracle/content-management-sdk';
The following command creates the delivery client:
return createDeliveryClient(serverconfig);
The src/scripts/services.js file contains all the code to get data for the application. There’s one main function for each page component in the application to get all the data for that page.
For rendering the images, the services.js provides a helper method to retrieve the sourceset for an asset that is constructed from the renditions for the asset.
function getSourceSet(asset) {
const urls = {};
.srcset = '';
urls.jpgSrcset = '';
urlsif (asset.fields && asset.fields.renditions) {
.fields.renditions.forEach((rendition) => {
assetaddRendition(urls, rendition, 'jpg');
addRendition(urls, rendition, 'webp');
;
})
}// add the native rendition to the srcset as well
.srcset += `${asset.fields.native.links[0].href} ${asset.fields.metadata.width}w`;
urls.native = asset.fields.native.links[0].href;
urls.width = asset.fields.metadata.width;
urls.height = asset.fields.metadata.height;
urlsreturn urls;
}
Home Page Data
The home page requires several data calls to get all of its data:
- First we query for items in the channel specified in .env.
- For each of the topic items, we fetch its details.
Open src/scripts/services.js and find the getTopicsListPageData() function, which gets all of the data for the home page.
export function getTopicsListPageData() {
const client = getClient();
return fetchHomePage(client)
.then((data) => (
getRenditionURLs(client, data.logoID)
.then((renditionUrls) => {
.companyThumbnailRenditionUrls = renditionUrls;
datareturn data;
});
)) }
The fetchHomePage() function, called by the getTopicsListPageData() function, gets all the items in the channel. This gets the logo ID, the company name, the about and contact URLs, and a list of topics.
function fetchHomePage(client) {
return client.queryItems({
q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
.then((data) => {
})const logoID = data.items[0].fields.company_logo.id;
const title = data.items[0].fields.company_name;
const aboutUrl = data.items[0].fields.about_url;
const contactUrl = data.items[0].fields.contact_url;
const { topics } = data.items[0].fields;
const promises = [];
.forEach((origTopic) => {
topics// add a promise to the total list of promises to get the full topic details
.push(
promisesfetchTopic(client, origTopic.id)
.then((topic) => topic),
;
);
})
// execute all the promises returning a single dimension array of all
// of the topics and the other home page data
return Promise.all(promises)
.then((allTopics) => (
{,
logoIDcompanyTitle: title,
,
aboutUrl,
contactUrltopics: flattenArray(allTopics),
}.catch((error) => logError('Fetching topics failed', error));
)).catch((error) => logError('Fetching home page data failed', error));
}) }
The fetchTopic() function is then called for each topic ID to get the full topic details.
function fetchTopic(client, topicId) {
return client.getItem({
id: topicId,
expand: 'fields.thumbnail',
.then((topic) => {
}).renditionUrls = getSourceSet(topic.fields.thumbnail);
topicreturn topic;
.catch((error) => logError('Fetching topic failed', error));
}) }
getTopicsListPageData() also calls getRenditionURLs() to get the URL of the image to render.
function getRenditionURLs(client, identifier) {
return client.getItem({
id: identifier,
expand: 'fields.renditions',
.then((asset) => getSourceSet(asset))
}).catch((error) => logError('Fetching Rendition URLs failed', error));
}
Topic Page Data
The topic page receives a topic ID and requires several data calls to get all of its data:
- Get all the articles for the specified topic.
- For each article, get its rendition URLs.
Open src/scripts/services.js and find the fetchTopicArticles(topicId) function, which is used to get all of the data for the topic page.
export function fetchTopicArticles(topicId) {
const client = getClient();
return client.queryItems({
q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
orderBy: 'fields.published_date:desc',
.then((data) => {
})const promises = [];
const articles = data.items;
.forEach((article) => {
articles// add a promise to the total list of promises to get the article url
.push(
promisesgetRenditionURLs(client, article.fields.image.id)
.then((renditionUrls) => {
.renditionUrls = renditionUrls;
articlereturn {
...article,
;
},
});
);
})
// execute all the promises and return all the data
return Promise.all(promises)
.then((allArticles) => ({
,
topicIdarticles: flattenArray(allArticles),
;
})).catch((error) => logError('Fetching topic articles failed', error));
}) }
The fetchTopicArticles() method also uses the getRenditionURLs() as seen previously, to get the image for the article.
Article Page Data
The article page receives an article ID and requires several data calls to get all of its data:
- Get the article details for the specified article. For each article, get its rendition URLs.
- Get the rendition URLs for the author avatar.
Open src/scripts/services.js and find the fetchArticleDetails(articleId) function, which gets the data for the article page.
export function fetchArticleDetails(articleId) {
const client = getClient();
return client.getItem({
id: articleId,
expand: 'fields.author,fields.image',
.then((article) => {
})const title = article.fields.author.name;
const date = article.fields.published_date;
const content = article.fields.article_content;
const imageCaption = article.fields.image_caption;
const { name } = article;
const renditionUrls = getSourceSet(article.fields.image);
const avatarID = article.fields.author.fields.avatar.id;
// Get the author's avatar image
return getRenditionURLs(client, avatarID)
.then((authorRenditionUrls) => (
// return an object with just the data needed
{id: articleId,
,
name,
title,
date,
content,
imageCaption,
renditionUrls,
authorRenditionUrls
};
)).catch((error) => logError('Fetching article details failed', error));
}) }
The fetchArticleDetails() method also uses the getRenditionURLs() as seen previously, to get the avatar image.
Now that we have our data queries, we can render the responses in our React components.
Client-Side Versus Server-Side Rendering
With client-side rendering (CSR), the client is responsible for building and rendering the content of a web page using JavaScript. With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client.
When the web page is requested from the server in client-side rendering, the HTML document returned contains skeleton HTML and no actual content. It contains a reference to a JavaScript bundle, which the client then requests from the server. On receiving this bundle, the client executes the JavaScript and populates the web page. Until the client has finished executing the JavaScript, all the user sees is a blank web page. One downside of client-side rendered applications is that when some web crawlers index the site, there is no actual content to index.
With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client. The advantage of this is that web crawlers can index the entire content on the web page.
React Blog Application Flow
The flow of the React blog application is as follows:
- The client makes a request to the server for a given route.
- The Express server receives the request.
- The Express server then performs the following tasks:
- It determines which components will be rendered for the given route, and calls the component’s fetchInitialData function to get all of the data for that component.
- It creates a string of all the content to render. (Each component will be asked to render to produce its HTML markup.)
- It creates an HTML document that contains the folowing items:
- The string of content to render
- A link to a style sheet, if applicable
- A script tag containing the client-bundle.js that the client will need
- The data obtained from all the components, serialized as JSON
- The server then returns the HTML to the client.
- The client receives the HTML and renders it. The user will see a fully formed web page.
- The JavaScript in the HTML will store the data in the web browser window on the client.
- The client requests the client-bundle.js file from the server. After receiving it, the client runs the JavaScript in the bundle.
- It “hydrates” the HTML, adding in any client-side JavaScript, such as event listeners.
- Each component being rendered sees if their data is stored on the window. If it is, that data is used; otherwise, the component gets the data it needs by making requests to the Oracle Content Management server via the Content SDK.
- If the HTML document contained a style sheet, the client requests the style sheet.
Viewing the source of the web page, you will see all the content in the HTML, indicating that the page was rendered on the server.
Note: This sample application gets the data in the root components and then passes the data down to any child component that needs it. An alternative is to use a state-management tool, such as Redux, which puts the data in a store, and any component can request the data from that store.
Server-Side Express Server and Rendering
The server application makes use of an Express server to receive the request, generate a React application instance, generate the HTML page, and return the response.
The Express server file is located at src/server/server.js.
The Express server accepts all requests and then uses React’s react-router-dom matchPath() to get the component that will render for the specified route. This in turn would call that component’s fetchInitialData method to get that component’s data, returning a promise. The promise is executed and a context object is created to contain the data. A renderer is then called to generate the HTML page before returning the HTML content to the client.
.get('*', (req, res) => {
serverconst activeRoute = Routes.find((route) => matchPath(req.url, route)) || {};
const promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData(req)
: Promise.resolve();
.then((data) => {
promiseconst context = { data, requestQueryParams: req.query };
// get the content to return to the client
const content = renderer(req, context);
// if the route requested was not found, the content object will have its "notFound"
// property set, therefore we need to change the response code to a 404, not found
if (context.notFound) {
.status(404);
res
}
// send the response
.send(content);
res;
}); })
The renderer is located at src/server/renderer.jsx and it uses React’s react-dom/server renderToString() to get a string of all the content being rendered.
// generate the HTML content for this application
const content = renderToString(
<StaticRouter context={context} location={req.path} basename={process.env.BASE_URL}>
<div>{renderRoutes(Routes)}</div>
</StaticRouter>,
; )
The context object passed to the renderer is passed to the server-side router, StaticRouter. During server-side rendering, any component is able to get the data from the component’s props.
this.props.staticContext.data
The renderer returns the HTML markup which contains the React content, the serialized data and a reference to the JavaScript bundle to run on the client.
<body>
<div id="root">${content}</div>
<script>
window.INITIAL_DATA = ${serialize(context.data)}
</script>
<script src="${clientBundleFile}"></script>
</body>
When the client receives the HTML, the data will be made available in the window and the client will request the client bundle from the server.
Client-Side Rendering
The client-side rendering code is located in src/client/main.jsx. This code goes through all the HTML of the web page, adding in any client-side JavaScript code.
This process is called hydrating.
.hydrate(
ReactDOM<BrowserRouter basename={process.env.BASE_URL}>
<div>{renderRoutes(Routes)}</div>
</BrowserRouter>,
document.querySelector('#root'),
; )
React Components
React uses a technology known as JSX, which is an HTML-like syntax extension to JavaScript, to render content. Even though you can write pure JavaScript to render data from Oracle Content Management, we strongly recommend that you use JSX.
The blog application breaks down each page into a number of smaller components.
The next few sections provide an overview of how React renders our application in each of our components:
- IS_BROWSER Variable
- Routes File
- TopicsListPage Component
- Header Component
- TopicsListItem Component
- ArticesListPage Component
- ArticesListItem Component
- ArticleDetailsPage Component
- Breadcrumbs and Breadcrumb Components
IS_BROWSER Variable
Webpack is used to bundle the client and server code. There’s a configuration file instructing Webpack on how to create each bundle.
Open the configuration file for the client bundle, webpack.client.config.js. At the bottom of the file, a variable is set to indicate that the application is running in a browser.
new webpack.DefinePlugin({
'process.env.IS_BROWSER': true,
, })
Open the configuration file for the server bundle, webpack.server.config.js. At the bottom of the file, the same variable is set to indicate that the application is not running in a browser. This variable can be accessed from anywhere in the React application code to determine if the application is rendering on the server or in the client.
Routes File
In our site, we want to provide three routes:
- The home page, which consists of the topics list
- The topic page, which displays all the articles for the selected topic
- The individual article page, displaying the selected article
The src/pages/Routes.js file defines the routes for the application. Here we’re using the ES6 spread operator for the first three pages references. This is because the imports for these items are objects containing the component and its fetchInitialData function (if it has one), rather than just the component. The following sections on each of these components show why an object is being exported from the component files rather than from the component itself.
export default [
{...TopicsListPage,
path: '/',
exact: true,
title: 'Topics',
,
}
{...ArticlesListPage,
path: '/articles/:topicId',
exact: true,
title: 'Articles',
,
}
{...ArticleDetailsPage,
path: '/article/:articleId',
exact: true,
title: 'Article',
,
}
{,
NotFoundPage,
}; ]
TopicsListPage Component
Any component in the pages directory is a route for the application. Any data required for a route must be obtained by these root components.
The Home page consists of a list of topics in a channel. It is rendered by the TopicsListPage component, located at src/pages/TopicsListPage.jsx.
The component imports the API to get data from the services.js file.
import { getTopicsListPageData } from '../scripts/services';
The constructor checks to see if the application is running on the client or the server, using the process.env.IS_BROWSER variable set in the Webpack bundling files. If the component is rendering in the client, the data is obtained from the window.
Note: If a user navigates to a page using client-side routing, server-side rendering will not occur. Instead, the content will be rendered using client-side rendering. As a result, the window will not contain any data, and the client will have to make a server call to get it.
If the component is being rendered on the server, the data is obtained from this.props.staticContext; that is, the data passed from the Express server file. The data, or default values, are then stored on the component’s state.
constructor(props) {
super(props);
let data;
if (process.env.IS_BROWSER) {
= window.INITIAL_DATA;
data delete window.INITIAL_DATA;
else {
} const { staticContext } = this.props;
= staticContext.data;
data
}
this.state = {
,
dataloading: !data,
;
} }
During server-side rendering, fetchInitialData is called to get the data from the server. It returns a promise to the calling code, the Express server code.
function fetchInitialData() {
return getTopicsListPageData();
}
During client-side rendering, componentDidMount is called. (This method is not called during server-side rendering). If the component does not already have the data, it is obtained from the server and stored on the component’s state.
// client side only : if this component doesn't already have its data, load it
componentDidMount() {
document.title = 'Topics';
const { data } = this.state;
if (!data) {
this.fetchData();
}
}
// Client Side Data Fetching: called from Client when doing client side routing/hydration
fetchData() {
this.setState(() => ({
loading: true,
;
}))
getTopicsListPageData()
.then((data) => {
this.setState({
,
dataloading: false,
;
});
}) }
In the render() method, you can see that the data to render is obtained from the component’s state.
At the bottom of the file and object is exported, this object contains the fetchInitialData function and the TopicsListPage component.
export default {
,
fetchInitialDatacomponent: TopicsListPage,
; }
Header Component
The TopicsListPage component uses the Header component to display the company title, company logo, and the Contact Us/About Us links.
It is located at src/components/Header.jsx and receives all of its data as properties. It does not get any additional data from the server.
TopicsListItem Component
The TopicsListPage component uses the TopicsListItem component to display the individual topic in the list.
The TopicsListItem component, located at src/components/TopicsListItem.jsx, receives all of its data as properties. It does not get any additional data from the server.
ArticlesListPage Component
The Topic page displays the articles in the topic whose ID is passed into the component on the URL. It is rendered by the ArticlesListPage component, located at src/pages/ArticlesListPage.jsx.
The component imports the API to get the data from the services.js file.
import { fetchTopicArticles } from '../scripts/services';
Like the TopicsListPage component, the constructor checks to see if the application is running in the browser or on the server, using the process.env.IS_BROWSER variable set in the Webpack bundling files. If the component is rendering in the client, the data is obtained from the window.
The constructor also gets the URL search query parameters, based on whether server-side or client-side rendering is occurring. For server-side rendering, the URL search query parameters are obtained from this.props.staticContext; that is, the data passed from the Express server file. For client-side rendering, this information is on the location object in the component props.
constructor(props) {
super(props);
const { match } = this.props;
const { topicId } = match.params;
let data;
let topicName;
if (process.env.IS_BROWSER) {
= window.INITIAL_DATA;
data delete window.INITIAL_DATA;
const { location } = this.props;
const params = new URLSearchParams(location.search);
= params.get('topicName');
topicName else {
} const { staticContext } = this.props;
= staticContext.data;
data = staticContext.requestQueryParams.topicName;
topicName
}
this.state = {
,
dataloading: !data,
,
topicName,
topicId;
} }
The fetchInitialData function is called during server-side rendering to get the data from the server. It uses the request passed in to get the topic ID from the URL (the last path in the URL).
function fetchInitialData(req) {
return fetchTopicArticles(req.path.split('/').pop());
}
During client-side rendering, componentDidMount is called. (This method is not called during server-side rendering.) It checks whether data has been obtained, and if it hasn’t, then fetchData() is called.
// executed client side only
componentDidMount() {
document.title = 'Articles';
const {data, topicId } = this.state;
if (!data) {
this.fetchData(topicId);
}
}
// Client Side Data Fetching: called from Client when doing client-side routing/hydration
fetchData(topicId) {
this.setState(() => ({
loading: true,
;
}))
fetchTopicArticles(topicId)
.then((data) => this.setState(() => ({
,
dataloading: false,
;
}))) }
In the render() method, you can see that the data to render is obtained from the component’s state.
Like the TopicsListPage component, the ArticlesListPage component exports an object containing the fetchInitialData function and the component.
export default {
,
fetchInitalDatacomponent: ArticlesListPage,
; }
ArticlesListItem Component
The ArticlesListPage component uses the ArticlesListItem component to display the individual articles in the list.
The ArticlesListItem component is located at src/components/ArticlesListItem.jsx and receives all of its data as properties. It does not get any additional data from the server.
ArticleDetailsPage Component
The Article page displays details of the article whose ID is passed on the URL. It is rendered by the ArticleDetails component, located at src/pages/ArticleDetailsPage.jsx.
The component imports the API to get the data from the services.js file.
import { fetchArticleDetails } from '../scripts/services';
The constructor for this is similar to the ArticlesListPage constructor.
constructor(props) {
super(props);
let data;
let topicName;
let topicId;
if (process.env.IS_BROWSER) {
= window.INITIAL_DATA;
data delete window.INITIAL_DATA;
const { location } = this.props;
const params = new URLSearchParams(location.search);
= params.get('topicName');
topicName = params.get('topicId');
topicId else {
} const { staticContext } = this.props;
= staticContext.data;
data = staticContext.requestQueryParams.topicName;
topicName = staticContext.requestQueryParams.topicId;
topicId
}
this.state = {
,
dataloading: !data,
,
topicId,
topicName;
} }
The fetchInitialData function is called during server-side rendering to get the data from the server. It uses the request passed in to get the article ID from the URL (the last path in the URL).
function fetchInitialData(req) {
return fetchArticleDetails(req.path.split('/').pop());
}
During client-side rendering, componentDidMount is called. (This method is not called during server-side rendering.) It checks if data has been obtained, and it if hasn’t, then fetchData() is called.
// executed client side only
componentDidMount() {
document.title = 'Article';
const { match } = this.props;
const { data } = this.state;
if (!data) {
this.fetchData(match.params.articleId);
}
}
// Client Side Data Fetching: called from Client when doing client side routing/hydration
fetchData(articleId) {
this.setState(() => ({
loading: true,
;
}))
fetchArticleDetails(articleId)
.then((data) => this.setState(() => ({
,
dataloading: false,
;
}))) }
In the render() method, you can see that the data to render is obtained from the component’s state.
Like the TopicsListPage component, the ArticleDetailsPage component exports an object containing the fetchInitialData function and the component.
export default {
,
fetchInitalDatacomponent: ArticleDetailsPage,
; }
Breadcrumbs and Breadcrumb Components
Both the TopicsListPage and ArticleDetailsPage components use the Breadcrumbs and Breadcrumb components to display the breadcrumbs at the top of the page, enabling the user to go back to the Topic page or the Home page. Both components receive all their data as properties; they do not get any additional data from the server.
Step 3: Prepare Your Application for Deployment
Now that we’ve built our React blog site, we need to see it in a local development server so we can debug any issues and preview the application before it goes live.
Prepare the application for deployment in three steps:
- Build the application using Webpack
- Run the application using Node
- Use scripts to build and run the application in development and production
Build the Application Using Webpack
Webpack is used to bundle the application. It creates two JavaScript bundles: server-bundle.js, which is run on the server, and client-bundle.js, which is downloaded and run on the client.
The React blog application has three Webpack configuration files:
- webpack.base.config.js is merged in with both the client and server Webpack configurations.
- webpack.client.config.js bundles the code for the client.
- webpack.server.config.js bundles the code for the server.
To build the client bundle, you must specify the client Webpack configuration:
webpack --config webpack.client.config.js
To build the server bundle, you must specify the server Webpack configuration:
webpack --config webpack.server.config.js
Run the Application Using Node
Once the bundles have been created, the server bundle will be located in the dist directory. You can start the server by running the following command:
node dist/server-bundle.js
Use Scripts to Build and Run the Application in Development and Production
The package.json file located at the root of the project contains scripts that make it easier to build the bundles and run the application.
Development
You can use the dev script during development:
npm run dev
This script builds the client and server bundles and starts the application in a local server. Webpack will watch for code changes and recreate the client and server bundles if required.
Production
For production, the build script would be used to build the client and server bundles:
npm run build
When the script completes, the application can be run using the following command:
npm run start
Build a Blog in React with Headless Oracle Content Management
F38761-05
July 2021
Copyright © 2021, Oracle and/or its affiliates.
Primary Author: Oracle Corporation