Build a Blog 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 blog app.

In this tutorial, we’ll build a simple blog 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:

  1. Prepare Oracle Content Management
  2. Build the Blog in React Native
  3. 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:

What We’re Building

Our blog will consist of three screens that lets visitors explore blog articles organized into topics. The first screen, the home screen, will consist of 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 Native blog that consumes content from Oracle Content Management.

This is what the home screen will look like at the end of this tutorial:

This image shows the home screen for Cafe Supremo demo site with a list of the available topics.

The second page, the topic screen, shows previews of each blog article that belongs to a topic. Here’s how an individual topic screen will look:

This image shows a topic screen called ‘How To Make Coffee’ with a list of the available articles for that topic.

Lastly, the article screen renders the final blog article, including information about the blog’s author. Here’s how an individual article page will look:

This image shows an individual article page, with the content and an author reference.

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 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:

  1. Create a channel and asset repository.
  2. Create a content model using either of two methods:

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:

  1. Log in to the Oracle Content Management web interface as an administrator.

  2. Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.

    This image shows the Publishing Channels option selected in the dropdown menu in the Content page header.

  3. 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.

    This image shows the publishing channel definition panel, with ‘OCEGettingStartedChannel’ in the channel name field.

  4. Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.

    This image shows the Repositories option selected in the dropdown menu in the Content page header.

  5. In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEGettingStartedRepository’ for the purpose of this tutorial.

    This image shows the repository definition panel, with ‘OCEGettingStartedRepository’ in the repository name field.

  6. 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.

    This image shows the repository definition panel, with ‘OCEGettingStartedChannel’ in the Publishing Channels field.

Create a Content Model

The next step is to create a content model. You can use either of two methods:

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:

  1. 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.

  2. Log in to the Oracle Content Management web interface as an administrator.

  3. 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.

    This image shows the Repositories page, with the OCEGettingStartedRepository item selected.

  4. Upload OCEGettingStarted_data.zip from your local computer to the Documents folder.

    This image shows the upload confirmation screen for the OCEGettingStarted_data.zip file.

  5. Once it’s uploaded, select OCEGettingStarted_data.zip and click OK to import the contents into your asset repository.

    This image shows the selected OCEGettingStarted_data.zip file with the OK button enabled.

  6. 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.

    This image shows the OCEGettingStartedRepository repository, with all assets that were just imported.

  7. 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.

    This image shows the OCEGettingStartedRepository repository, with all assets selected and the Publish option in the action bar visible.

  8. Before publishing, you need to validate all the assets. First add OCEGettingStartedChannel as a selected channel, and then click the Validate button.

    This image shows the Validation Results page, with the OCEGettingStartedChannel channel added in the Channels field, all assets to be validated, and the Validate button enabled.

  9. 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.

    This image shows the Validation Results page, with the OCEGettingStartedChannel channel added in the Channels field, all assets validated, and the Publish button enabled.

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.)

This image shows the Assets page, with all assets pubished.

After importing the Oracle Content Management Samples Asset Pack, you can start building the blog in React Native.

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 screen for our blog. This home page consists of a list of blog topics that should be included on the screen.

This image shows the home screen for the Cafe Supremo demo site.

To create content types for the content model:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
  3. Click Create in the top right corner.
  4. Choose to create a content type (not a digital asset type). Repeat this for all required content types.

This image shows the Create Asset Type dialog in the Oracle Content Management web interface.

We’ll create four content types, each with its own set of fields:

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:

This image shows the definition for the content type ‘OCEGettingStartedHomePage’. It includes these data fields: Company Name, Company Logo, Topics, Contact URL, and About URL.

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:

This image shows the definition for the content type ‘OCEGettingStartedTopic’. It includes this data field: Thumbnail.

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:

This image shows the definition for the content type ‘OCEGettingStartedAuthor’. It includes this data field: Avatar.

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:

This image shows the definition for the content type ‘OCEGettingStartedArticlePage’. It includes these data fields: Published Date, Author, Image, Image Caption, Article Content, and Topic.

Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEGettingStartedRepository:

  1. Log in to the Oracle Content Management web interface as an administrator.
  2. Navigate to OCEGettingStartedRepository.
  3. Edit the repository and, under Asset Types, specify all four newly created content types. Click the Save button to save the changes.

This image shows the Edit Repository page in Oracle Content Management, with the four newly created content types associated with the OCEGettingStartedRepository repository.

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.

This image shows content items on the Assets page in the Oracle Content Management web interface, with options on the left for collections, channels, languages, types, content item selection, and status.

Task 2: Build the Blog in React Native

To consume our Oracle Content Management content in a React Native application, we can use the React Native blog 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 blog in React Native consists of these steps:

  1. Clone the sample repository and install dependencies
  2. Configure the React Native application
  3. Use the Oracle Content Management REST API to fetch content

Clone the Sample Repository and Install Dependencies

The React Native 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-samples/oce-reactnative-blog-sample.git
cd oce-reactnative-blog-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 OCMBlog
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": "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.

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 blog 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 getItem(args) {
  let url = `${getContentServerURL()}items/`;

  // add the item identifier to the url
  if ('id' in args) {
    // using ID :   /item/{itemId}
    url += args.id;
  } else if ('slug' in args) {
    // using Slug : /item/.by.slug/{slug}
    url = `${url}.by.slug/${args.slug}`;
  }

  // add the channel token to the URL
  url = addChannelToURL(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 getRenditionURLFromServer(args) {
  let url = `${getContentServerURL()}assets/${args.id}/native`;
  url = addChannelToURL(url);
  return url;
}

The queryItems function is used to make a REST call like the following which is used to get the URL for the image for the home page.

GET content/published/api/v1.1/items?q=(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")&fields=all&channelToken={channelToken}

The queryItem function is used to make a REST call like the following, which is used to get a topic or an article.

GET content/published/api/v1.1/item{itemId}?fields=all&expand=all&hannelToken={channelToken}

The getRenditionURLFromServer function is used to make a REST call like the following, which is used to get a topic thumbnail, article thumbnail, and user avatar.

GET content/published/api/v1.1/assets/{assetId}/native?channelToken={channelToken}

The src/scripts/services.js file contains all the code to get data for the application.

Home Page Data

The home page requires several data calls to get all of its data:

  1. First we query for items in the channel specified in oce.dart.
  2. Fetch the details for each of the topic items.

Open src/scripts/services.js and find the queries below, which help to get all of the data for the home page.

  // Fetch the top level values to be displayed on the home page.
 queryItems({
    q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
  })

  // Fetch details about the specific topic
  getItem({
    id: topicId,
    expand: 'fields.thumbnail',
  })

Topic Page

The Articles screen shows all articles for a given topic. Again, we use queryItems, this time searching for content items of the type OCEGettingStartedArticle that reference the topic whose identifier was passed to the screen as a query parameter. The fetchArticles() in src/scripts/services uses this query:

queryItems({
    q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
    orderBy: 'fields.published_date:desc',
  })

Article Page

The individual article screen shows a single article, but the screen includes content from Author, which is a separate content type. To fetch one content item plus any content items it references, use getItem with the expand parameter set to fields.author. The fetchArticle() in src/scripts/services uses this query:

  getItem({
    id: articleId,
    expand: 'fields.author',
  })

Now that we have our data queries, we can render the responses in our React Native components.

React Native Components

The blog application breaks down each screen into a number of smaller components.

The next few sections provide an overview of how React Native renders our application in each of our screens:

Component Structure

There are two components for each screen in the application: a container component responsible for getting the data from the server and a view component responsible for rendering the view. For example, in the topics list screen the components are:

The following sections only cover the container 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:

Open the root component, located at src/components/App.js, and see the screen options.

<NavigationContainer theme={MyTheme}>

  {/* Set the screen titles to nothing, the titles will be updated in the components */}
  <Stack.Navigator
    initialRouteName="Topics"
    screenOptions={{
      headerStyle: {
        backgroundColor: AppColors.ACCENT,
      },
      headerTintColor: AppColors.WHITE,
    }}
  >
    <Stack.Screen
      name="Topics"
      component={TopicsListContainer}
      options={{ title: '' }}
    />
    <Stack.Screen
      name="Articles"
      component={ArticlesListContainer}
      options={{ title: '' }}
    />
    <Stack.Screen
      name="ArticleDetails"
      component={ArticleDetailsContainer}
      options={{ title: '' }}
    />
  </Stack.Navigator>

</NavigationContainer>
Topics List Container Component

As we saw previously, the topics screen consists of a list of individual topics. Open the topics list container component, located at src/components/ TopicsListContainer.js. Note the invocation of the fetchHomePage() method, which is defined as follows in src/scripts/services.js:

export function fetchHomePage() {
  return queryItems({
    q: '(type eq "OCEGettingStartedHomePage" AND name eq "HomePage")',
    fields: 'all',
  }).then((topLevelItem) => {
    if (topLevelItem != null
        && topLevelItem.items != null
        && topLevelItem.items.length > 0) {
      return {
        logoID: topLevelItem.items[0].fields.company_logo.id,
        title: topLevelItem.items[0].fields.company_name,
        topics: topLevelItem.items[0].fields.topics,
        aboutUrl: topLevelItem.items[0].fields.about_url,
        contactUrl: topLevelItem.items[0].fields.contact_url,
      };
    }
    return null;
  });
}

Back in our topics list container component, we retrieve what is necessary for rendering the home screen:

     fetchHomePage()
      .then((topLevelItem) => {
        if (this.mounted && topLevelItem == null) {
          this.setState({ error: true });
          return;
        }

        const topicIdentifiers = topLevelItem.topics.map((topic) => topic.id);

        if (this.mounted) {
          this.setState({
            topicIds: topicIdentifiers,
          });

          this.setUpHeader(
            topLevelItem.title,
            topLevelItem.aboutUrl,
            topLevelItem.contactUrl,
          );
        }
      })
      .then(() => this.setState({ loading: false }))
      .catch((error) => {
        this.setState({ error: true });
        console.error(error);
      })
Topic List Item Container Component

The topic list item container component represents the individual topic in the list. Open the topic list item container component, located at src/components/ TopicListItemContainer.js. Note the invocation of the fetchTopic() method, defined as follows in src/scripts/services.js:

export function fetchTopic(topicId) {
  return getItem({
    id: topicId,
    fields: 'all',
    expand: 'all',
  }).then((topic) => topic);
}

Once the topic has been obtained, we call getMediumRenditionURL() to get the URL for the topic’s thumbnail, which is defined as follows in src/scripts/services.js:

export function getMediumRenditionURL(identifier) {
  return getItem({
    id: identifier,
    fields: 'all',
    expand: 'all',
  }).then((asset) => {
    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];
    const url = self.href;
    return url;
  });
}

Back in our topic list item container component, we retrieve what is necessary for rendering each topic item.

     fetchTopic(id)
      .then((topic) => {
        // once the topic is obtained, fetch the URL for the topic's thumbnail
        getMediumRenditionURL(topic.fields.thumbnail.id)
          .then((thumbnailUrl) => {
            if (this.mounted) {
              this.setState({
                title: topic.name,
                description: topic.description,
                url: thumbnailUrl,
                loading: false,
              });
            }
          })
          .catch((error) => console.error(error));
      })
      .catch((error) => console.error(error));
Articles List Container Component

As for our list of articles on each individual topic screen, we need to retrieve the associated list of articles. Open the articles list container component, located at src/components/ ArticlesListContainer.js. Note the invocation of the fetchArticles() method, defined as follows in src/scripts/services.js:

export function fetchArticles(topicId) {
  return queryItems({
    q: `(type eq "OCEGettingStartedArticle" AND fields.topic eq "${topicId}")`,
    fields: 'all',
    orderBy: 'fields.published_date:desc',
  }).then((articles) => {
    if (articles != null) {
      return articles.items;
    }
    return null;
  });
}

Back in our articles list component, we retrieve what is necessary for rendering the list of articles.

    fetchArticles(topicId)
      .then((articles) => {
        if (this.mounted) {
          if (articles == null) {
            this.setState({ error: true });
          } else {
            this.setState({ articles });
          }
        }
      })
      .catch((error) => {
        this.setState({ error: true });
        console.error(error);
      })
      .then(() => this.setState({ loading: false }));
Article List Item Container Component

The article list item container component represents the individual article in the list. Open the article list item component, located at src/components/ArticleListItemContainer.js. Like the topic list item component, this component also uses getMediumRenditionUrl() method to retrieve the URL for the article thumbnail.

Article Detail Container Component

Finally, we need to render each individual article screen. Open the article detail component, located at src/components/ ArticleDetailsContainer. Note the invocation of the fetchArticle() method, defined as follows in src/scripts/services.js:

export function fetchArticle(articleId) {
  return getItem({
    id: articleId,
    expand: 'all',
  }).then((article) => article);
}

Back in our article detail component, we retrieve what is necessary for rendering the article. In the process, we also invoke and getRenditionURL()to get the image for the article, and we also invoke getMediumRenditionURL()to get the medium rendition of the user’s avatar:

    fetchArticle(articleId)
      .then((article) => {
        if (this.mounted) {
          this.setState({ article });
        }

        // get the article image URL
        getRenditionURL(article.fields.image.id)
          .then((renditionUrl) => {
            if (this.mounted) {
              this.setState({ articleImageUrl: renditionUrl });
            }

            // Get the author's avatar image
            getMediumRenditionURL(article.fields.author.fields.avatar.id)
              .then((thumbnailUrl) => {
                if (this.mounted) {
                  this.setState({ authorAvatarUrl: thumbnailUrl });
                  this.setState({ loading: false });
                }
              });
          });
      })
      .catch((error) => {
        this.setState({ error: true });
        console.error(error);
      });

Task 3: Prepare Your Application for Deployment

Now that we’ve built our React Native blog 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, see the sections on the React Native website for your machine and which mobile operating system you are 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 blog 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 blog 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.