Build an Image Gallery 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 gallery app.
In this tutorial, we’ll build a simple gallery 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 Image Gallery 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
Our image gallery will consist of several screens of images of food and drinks available at a coffee shop.
Categories are child nodes of a taxonomy and can be organized into hierarchies. For our image gallery, we want to show all available categories regardless of the organization. To accomplish this, we first need to find the available taxonomies, which we do using the REST API resource GET /published/api/v1.1/taxonomies.
Next, we need to get the set of categories for each of the taxonomies. This is done using the REST API GET /published/api/v1.1/taxonomies/{id}/categories.
To build the preview of a category, such as Bagels, we need to get a count of the number of images and the URLs of the first four images.
Our request to find the published assets in the category specifies the category criteria through a query string, as follows:
"(taxonomies.categories.nodes.id eq 892CD6BC4F654249A00CB7942EE8C773)"
Note: In addition to publishing the digital assets that we want to view, you also need to publish the taxonomies to the channel.
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
This tutorial is based on the assumption that you’ve created your asset repository and currently have an empty content model (that is, no content types created).
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.
- Import the Oracle Content Management Samples Asset Pack
- Upload Your Own Image Assets
- Create Taxonomies and Link Them to Image Assets
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 ‘OCEImageGalleryChannel’ 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 ‘OCEImageGalleryRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select OCEImageGalleryChannel to indicate to Oracle Content Management that content in the OCEImageGalleryRepository repository can be published to the OCEImageGalleryChannel 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. 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 OCEImageGallery_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 OCEImageGalleryRepository and click the Import Content button in the top action bar.
Upload OCEImageGallery_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEImageGallery_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 OCEImageGalleryRepository 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, OCEImageGalleryChannel.
Before publishing, you need to validate all the assets. First add OCEImageGalleryChannel 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 image gallery in React Native.
Upload Your Own Image Assets
For this tutorial, we’re using an asset repository called ‘OCEImageGalleryRepository’ to build the home page for our gallery site. This home page consists of the title ‘Image Gallery’ as well as image collection albums that have image assets inside.
To add image assets to the gallery asset repository:
Log in to the Oracle Content Management web interface.
Click Assets in the left navigation menu.
Open the OCEImageGalleryRepository repository.
Click Add in the upper right corner of the page to add image assets to the gallery asset repository.
Upload your own new assets from your local computer or choose existing assets already in Oracle Content Management.
Create Taxonomies and Link Them to Image Assets
You need to create a taxonomy in Oracle Content Management and then assign categories to the assets in your repository.
To create a taxonomy 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 Taxonomies from the selection list in the page header.
In the upper right corner, click Create to create a new taxonomy. Name the channel ‘OCEImageGalleryTaxonomy’ for the purpose of this tutorial.
Click Create.
Now build your taxonomy by adding categories. Click Add a category.
Name the parent category item ‘Food’, and add the following child categories:
- Breakfast
- Dessert
- Drinks
- Sandwiches
Click Done at the top right of the screen.
On the Taxonomies page, select the OCEImageGalleryTaxonomy taxonomy and click Promote in the actions bar to make it available for use in your asset repositories.
Next, edit the OCEImageGalleryRepository repository to enable the OCEImageGalleryTaxonomy taxonomy for that repository:
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.
Select and edit the OCEImageGalleryRepository repository.
In the Taxonomies field, select OCEImageGalleryTaxonomy, so you can assign categories from that taxonomy to the assets in the OCEImageGalleryRepository repository.
Click Save.
Then, assign taxonomy categories to each of the image assets in the OCEImageGalleryRepository repository:
Log in to the Oracle Content Management web interface.
Click Assets in the left navigation menu.
Open the OCEImageGalleryRepository repository.
Select one or more image assets, click More in the actions bar, and then choose Categories from the menu.
In the Categories panel, click Add Category. Search for the category name in the search bar or select a category from the taxonomy hierarchical structure, and click Add to assign the selected category. You can assign multiple categories to an asset.
After you’re done assigning taxonomies to all the image assets, select all assets in your repository and publish them to the OCEImageGalleryChannel channel.
Task 2: Build the Image Gallery in React Native
To consume our Oracle Content Management content in a React Native application, we can use the React Native gallery 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 image gallery 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 gallery 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-gallery-sample.git
cd oce-reactnative-gallery-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 OCMGallery
npm run init
Configure the React Native Application
In this React Native 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": "e0b6421e73454818948de7b1eaddb091"
}
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 OCEImageGalleryChannel.
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 image gallery 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 other REST calls are:
- getTaxonomies() to get taxonomies for the channel
- queryTaxonomyCategories() to get categories for the specified taxonomy
- getItems(args) to get a list of items based on SCIM search criteria
- getItem(args) to get a single item given its ID or SLUG
- getRenditionURL(args) to get the rendition URL of an asset based on its ID.
A function like getRenditionURL() is used to make a REST call like the following to get the actual rendition URL of an image:
GET /content/published/api/v1.1/assets/CONT8FE77BF7B91E4A19950D2F6EB5F39430/native?channelToken=5a2bacaadc85407aa2392d5cdea78ead
services.js
The src/scripts/services.js file contains functions to get the data we require in each component. These services call those REST APIs defined in src/scripts/content-rn.js.
Now that we have our data query, we can render the responses in our React Native components(#react-native-components).
React Native Components
The gallery application breaks down each page into a number of smaller components.
The next few sections provide an overview of how React Native renders our application in each of our components:
Root Component
The main entry point to this React Native application is the src/components/App.js file. This file defines the different screens in our application. In our site, we want to provide three screens:
- the home screen
- the image grid
- the image pager.
Open the root component, located at src/components/App.js, and see the screen options.
<NavigationContainer theme={MyTheme}>
<Stack.Navigator
initialRouteName="HomePage"
screenOptions={{
headerStyle: {
backgroundColor: AppColors.ACCENT,
},
headerTintColor: AppColors.WHITE,
}}
>
<Stack.Screen
name="HomePage"
component={HomePage}
options={{ title: 'Image Gallery' }}
/>
<Stack.Screen
name="ImageGrid"
component={ImageGrid}
options={{ title: '' }}
/>
<Stack.Screen
name="ImagePager"
component={ImagePager}
options={{ title: '' }}
/>
</Stack.Navigator>
</NavigationContainer>
HomePage and Gallery Component
As we saw previously, the home page consists of a list of categories for a taxonomy, with a preview of four items in that category. Open the home page container component, located at src/components/HomePage.js. Note the invocation of the fetchTaxonomies() and fetchCategories() method, which is defined as follows in src/scripts/services.js
export function fetchTaxonomies() {
return getTaxonomies().then((topLevelItem) => topLevelItem);
}
See that when the taxonomies are returned we call fetchCategories() method, which is defined as follows in src/scripts/services.js:
export function fetchCategories(taxonomyId) {
return queryTaxonomyCategories({
id: `${taxonomyId}`,
}).then((topLevelItem) => topLevelItem);
}
Back in our HomePage component, we retrieve what is necessary for rendering the home page:
fetchTaxonomies()
.then((topLevelItem) => {
// If the top level item was not found, display an error message
if (!topLevelItem) {
if (self.mounted) {
self.setState({
error: true,
errorMsg: 'There was an error fetching the taxonomies.',
});
return;
}
}
const taxonomyIds = topLevelItem.items.map((taxonomy) => taxonomy.id);
// If there are no taxonomies, display an error message
if (taxonomyIds.length === 0) {
if (self.mounted) {
self.setState({
error: true,
errorMsg: 'There are no published taxonomies in this repository.',
});
return;
}
}
// For each taxonomy, fetch the categories and append them to an array
taxonomyIds.forEach((taxonomyId, index) => {
fetchCategories(taxonomyId)
.then((categoriesTopItem) => {
categories = categories.concat(categoriesTopItem.items);
// update the state as you concat the categories.
if (categories.length !== 0 && self.mounted) {
self.setState({
categoriesArray: categories,
loading: false,
});
}
// if there are no categories, set error message accordingly
if (index === taxonomyIds.length - 1 && categories.length === 0 && self.mounted) {
self.setState({
error: true,
errorMsg: 'There are no published categories for taxonomies in this repository.',
});
}
})
.catch(() => {
self.setState({ error: true });
});
});
})
.catch(() => {
self.setState({ error: true });
});
And render the content using the render method:
<View onLayout={this.onTopViewLayout}>
<FlatList
data={this.addEmptyItemsToData()}
style={styles.flatListContainer}
renderItem={this.renderItem}
keyExtractor={(item) => item.id}
numColumns={numColumns}
key={numColumns}
/>
</View>
<View style={[styles.listItemBorder, styles.listItemContainer]}>
<Gallery key={item.id} category={item} navigation={navigation} />
</View>
The Gallery component is responsible for rendering the first four images in that category.
ImageGrid component
The ImageGrid component, on the other hand, displays all the images belonging to the specified category in a grid format. Open the ImageGrid component, located at src/components/ImageGrid.js. Note the invocation of the fetchItemsForCategory() method, defined as follows in src/scripts/services.js:
export function fetchItemsForCategory(categoryId, limit) {
return getItems({
q: `(taxonomies.categories.nodes.id eq "${categoryId}")`,
limit: limit ? 4 : 100,
totalResults: true,
}).then((topLevelItem) => topLevelItem)
.catch((error) => logError('Fetching items for category failed', error));
}
See that for each category item, we call the getMediumRenditionUrl () method, defined as follows in src/scripts/services.js:
export function getMediumRenditionUrl(identifier) {
return getItem({
id: identifier,
expand: 'fields.renditions',
}).then((asset) => {
let url = null;
if (asset.fields && asset.fields.renditions) {
const object = asset.fields.renditions.filter((item) => item.name === 'Medium')[0];
const format = object.formats.filter((item) => item.format === 'jpg')[0];
const self = format.links.filter((item) => item.rel === 'self')[0];
url = self.href;
}
return url;
}).catch((error) => logError('Fetching medium rendition URL failed', error));
}
Back in our ImageGrid component, we retrieve what is necessary for rendering the items in the category in a grid.
fetchItemsForCategory(id, false)
.then((topLevelItem) => {
const images = [];
// for each item, retrieve the rendition urls
topLevelItem.items.forEach((item) => {
retrieveRenditionURLs(item.id)
.then((renditionUrls) => {
if (renditionUrls != null) {
images.push({ renditionUrls, alt: item.name });
// Set the state so that it can be rendered
if (this.mounted) {
this.setState({
imagesArray: images,
loading: false,
});
if (images.length > 0) {
navigation.setOptions({ title: `${name} (${images.length} photos)` });
}
}
}
})
.catch(() => {
if (this.mounted) {
this.setState({ error: true });
}
});
});
})
.catch(() => {
if (this.mounted) {
this.setState({ error: true });
}
});
ImagePager component
The ImagePager component displays a full screen version of the image in a swiper. You can swipe left and right to see the other images in that category. The imagesArray is passed as a parameter from the previous screen, so this screen doesn’t need to do any network calls. Images are displayed in the render method as shown below:
<Swiper
style={styles.viewPager}
index={initialIndex}
showsButtons={showNavButtons}
orientation="horizontal"
showsPagination={false}
onIndexChanged={(index) => {
this.setState({ index });
}}
loop={false}
>
{imagesArray.map((img, i) => this.renderImage(img, i, headersValue))}
</Swiper>
Task 3: Prepare Your Application for Deployment
Now that we’ve built our React Native image gallery site, we need to deploy it on an emulator or 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 gallery 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 gallery 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 an Image Gallery in React Native with Headless Oracle Content Management
F74253-01
November 2022
Copyright © 2021, 2022, Oracle and/or its affiliates.
Primary Author: Oracle Corporation