Build a Minimal Site in React Native with Headless Oracle Content Management
Introduction
React Native is an open-source UI framework for writing mobile applications for iOS and Android. React Native can be a powerful tool for building applications that consume content from Oracle Content Management. Armed with the right content model, you can quickly build the React Native UI that make up a typical app.
In this tutorial, we’ll build a simple minimal site in React Native by leveraging Oracle Content Management as a headless CMS. This React Native sample is available on GitHub.
The tutorial consists of three steps:
- Prepare Oracle Content Management
- Build the minimal site in React Native
- Prepare your application for deployment
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 React Native tooling configured
What We’re Building
With React Native minimal, you can easily retrieve images and other content from your Oracle Content Management repository.
To take a look at what we’re building, here’s the end state of our tutorial, a basic React Native minimal site that consumes content from Oracle Content Management.
This is what the home screen will look like at the end of this tutorial:
This is what the Contact Us screen will look like at the end of this tutorial:
To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.
Task 1: Prepare Oracle Content Management
If you don’t already have an Oracle Content Management instance, see 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. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content.
To prepare Oracle Content Management:
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 ‘OCEMinimalChannel’ 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 ‘OCEMinimalRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select the OCEMinimalChannel channel to indicate to Oracle Content Management that content in the OCEMinimalRepository repository can be published to the OCEMinimalChannel channel. Click Save when you’re done.
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.
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 OCEMinimal_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 OCEMinimalRepository and click the Import Content button in the top action bar.
Upload OCEMinimal_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEMinimal_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 OCEMinimalRepository 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, OCEMinimalChannel.
Before publishing, you need to validate all the assets. First add OCEMinimalChannel 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.)
Task 2: Build the Minimal Site in React Native
To consume our Oracle Content Management content in a React Native application, we can use the React Native minimal site sample, which is available as an open-source repository on GitHub.
Note: Remember that using the React Native sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own React Native application.
Building the minimal site in React Native consists of these steps:
- Clone the sample repository and install dependencies
- Configure the React Native application
- Use the Oracle Content Management REST API to fetch content
Clone the Sample Repository and Install Dependencies
The React Native minimal site 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-samples/oce-reactnative-minimal-sample.git
cd oce-reactnative-minimal-sample
Now that we have our code base, we need to download dependencies for the application and merge with a template project. Run the following commands:
npm install
npx react-native init OCMMinimal
npm run init
Configure the React Native Application
In this React Native minimal sample, you need to configure a few pieces of information so that your REST API requests can target the correct instance URL and API version with the correct channel token. These values defined in src/config/content.json are used by the functions defined in src/scripts/content-rn.js to establish the endpoint for the REST API.
You’ll see the following information in src/config/content.json:
{
"serverUrl": "https://samples.mycontentdemo.com",
"apiVersion": "v1.1",
"channelToken": "ba0efff9c021422cb134c2fd5daf6015"
}
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 OCEMinimalChannel.
We also need to configure which images are to be used throughout the application. In src/config/data.js file you’ll see the following:
const appConfig = {
logo: 'Logo.png',
footerLogo: 'Powered_by_OCE.png',
homePage: 'Banner1.jpg',
contactUs: 'Banner2.jpg',
};
export default appConfig;
Change the name of each image to reflect the values in your instance.
Use the Oracle Content Management REST API to Fetch Content
The REST API for Content Delivery provides access to published assets in Oracle Content Management. Published assets include content items and digital assets, as well as their renditions. We can now leverage the REST API for Content Management to fetch content so that we can render it in our minimal React Native application.
The src/scripts/content-rn.js file has methods for connecting to the server specified in the content.json file using the REST API and returning the response from it.
function getContentServerURL() {
const path = DELIVERY_API_URL_PATH;
return `${data.serverUrl}${path}${data.apiVersion}/`;
}
function addChannelToURL(currUrl) {
return `${currUrl}?channelToken=${data.channelToken}`;
}
async function callServer(url) {
const requestOptions = {
method: 'GET',
};
return fetch(url, requestOptions);
}
The content-rn.js also provides helper methods to query items and retrieve the native url rendition for an asset.
export function queryItems(args) {
let url = `${getContentServerURL()}items`;
url = addChannelToURL(url);
// add query params to the url
Object.entries(args).map((entry) => {
const [key, value] = entry;
if (key !== 'id' && key !== 'slug') {
url = `${url}&${key}=${value}`;
}
return true;
});
return callServer(url)
.then((response) => response.json())
.then((json) => json)
.catch((error) => {
console.error(error);
});
}
export function getRenditionURL(args) {
let url = `${getContentServerURL()}assets/${args.id}/native`;
url = addChannelToURL(url);
return url;
}
The queryItems function is used to make a REST API call like the following, which is used to get the URL for the image on the home page.
GET /content/published/api/v1.1/items?q=(name%20eq%20%22Banner1.jpg%22)&fields=all&channelToken=5a2bacaadc85407aa2392d5cdea78ead
The getRenditionURL function is used to make a REST API call like the following to get the actual rendition URL of an image.
GET /content/published/api/v1.1/assets/CONT8FE77BF7B91E4A19950D2F6EB5F39430/native?channelToken=5a2bacaadc85407aa2392d5cdea78ead
The src/scripts/services.js file contains all the code to get data for the application.
Fetching Image Data
Open src/scripts/services.js and find the function below, which helps to get all of the images for this app.
// Get all the images needed for the app
export default function fetchImageURLs(imageNames) {
// Build up the query predicate of the format :
// 'name eq "name1" OR name eq "name2" OR name eq "name3"'
let predicate = '';
for (let i = 0; i < imageNames.length; i += 1) {
if (i > 0) {
predicate += ' OR ';
}
predicate += `name eq "${imageNames[i]}"`;
}
const queryString = `(${predicate})`;
// Search for the items and get the Rendition URL for each item
return queryItems({
q: queryString,
}).then((result) => {
const imageURLs = {};
const guids = result.items;
for (let i = 0; i < guids.length; i += 1) {
const url = getRenditionURL({
id: guids[i].id,
});
imageURLs[guids[i].name] = url;
}
return imageURLs;
}).catch((error) => logError('Fetching images failed', error));
}
Now that we have our data queries, we can render the responses in our React Native components.
React Native Components
The minimal application breaks down each page into a number of smaller components, some of which are used on both the Home and Contact Us pages.
The next few sections comprise an overview of how React Native renders our application in each of our components:
- Root component
- Image with text component
- Home page and welcome component
- Contact us page, connect with us and locations components
Root Component
The main entry point to this React Native application is the src/App.js file. This file defines the different screens in our application.
In our site, we want to provide two screens:
- The home screen
- The contact us screen
We’ll also have a drawer that opens to enable the user to change between screens.
Open the root component, located at src/App.js, and see the screen options.
<NavigationContainer>
<Drawer.Navigator
drawerContent={(props) => (
// eslint-disable-next-line react/jsx-props-no-spreading
<DrawerContents {...props} logo={navDrawerLogoUrl}/>
)}
initialRouteName="Home"
screenOptions={{
drawerActiveTintColor: '#C0D600',
drawerInactiveTintColor: '#797979',
drawerLabelStyle: {textTransform: 'uppercase'},
}}
>
<Drawer.Screen
name="Home"
component={HomeNavigator}
initialParams={{
imageUrl: homePageImageUrl,
companyLogoUrl,
}}
/>
<Drawer.Screen
name="Contact Us"
component={ContactUsNavigator}
initialParams={{
imageUrl: contactUsImageUrl,
companyLogoUrl,
}}
/>
</Drawer.Navigator>
</NavigationContainer>
In the componentDidMount() method, see that it gets all the images required for the application.
fetchImageURLs([
appConfig.logo,
appConfig.footerLogo,
appConfig.homePage,
appConfig.contactUs,
])
.then((urls) => {
if (this.mounted) {
this.setState({
companyLogoUrl: urls[appConfig.logo],
navDrawerLogoUrl: urls[appConfig.footerLogo],
homePageImageUrl: urls[appConfig.homePage],
contactUsImageUrl: urls[appConfig.contactUs],
dataLoading: false,
});
}
})
.catch((error) => {
console.error(error);
});
Image With Text Component
The image with text component, located at src/components/ImageWithText.js, is used by both the home page and contact us page components. It consists of an image with two text items displayed on top of the image. It can also display a button below the text if required, as in the case of the Contact Us page. This component has all data passed into it and simply renders the content. It doesn’t get any data from Oracle Content Management.
Home Page and Welcome Component
The home screen contains an image with fixed text overlaying the image and a welcome message.
The home page component, located at src/components/Home.js, has all the data passed into it, and therefore doesn’t make any server calls.
Contact Us Page, Connect With Us and Locations Components
The Contact Us screen contains an image with fixed text and button overlaying the image, connect with us details, and office locations text.
The contact us page component, located at src/components/ContactUs.js, has all the data passed into it, and therefore doesn’t make any server calls.
Task 3: Prepare Your Application for Deployment
Now that we’ve built our React Native minimal application, we need to test it in a mobile simulator or real device so we can debug any issues and preview the application before it goes live.
This sample application was created using React Native CLI. Before you can test your React Native application on mobile simulators or devices, you need to set up the mobile tooling. For details, see the sections on the React Native website for your device and mobile operating system that you’re testing.
Note: iOS applications can only be built and tested using a Mac computer.
Here’s an example of the command to test on a simulator or real device, which must be run from the application root folder:
npm run android
or
npm run ios
See the React Native documentation for details on packaging and deploying React Native applications.
Conclusion
In this tutorial, we created a minimal site in React Native, which can be found on GitHub. This site uses Oracle Content Management as a headless CMS. After setting up and configuring Oracle Content Management with a channel of published content for the minimal site tutorial, we installed and ran the React Native site to fetch the required content and build the site.
For more information on React Native, go to the React Native website.
Learn about important Oracle Content Management concepts in the documentation.
You can find more samples like this on the Oracle Content Management Samples page in the Oracle Help Center.
Build a Minimal Site in React Native with Headless Oracle Content Management
F74251-01
November 2022
Copyright © 2021, 2022, Oracle and/or its affiliates.
Primary Author: Oracle Corporation