Build a news app using TypeScript, React and Contentstack

TypeScript is designed for development of large applications and it converts the source code to JavaScript. React is a Javascript library for building better user interfaces.

This sample website is developed using TypeScript and React, and uses Contentstack’s JavaScript Delivery SDK. It uses Contentstack to store and deliver the content of the website.

Screenshots

TS_ss.jpg

Quickstart

Here’s a quick guide on how to create this demo website using TypeScript, React, and Contentstack.

Prerequisites

Note: For this tutorial, we have assumed that you are familiar with Contentstack, TypeScript, and React. If not, then please refer to the respective docs (Contentstack docs, TypeScript docs, and React docs) for more details.

In this tutorial, we will first go through the steps involved in configuring Contentstack and then look at the steps required to customize and use the presentation layer.

  1. Create a stack

    Log in to your Contentstack account, and create a new stack. This stack will hold all the data, specific to your website. Learn more on how to create a stack.

  2. Add a publishing environment

    To add an environment in Contentstack, navigate to Settings -> Environment, and click on the + New Environment tab. Provide a suitable name for your environment, say “production.” Specify the base URL (e.g., “http://YourDomainName.com”), and select the language (e.g., English - United States). Then, click on Save. Read more about environments.

  3. Import content types

    A content type is like the structure or blueprint of a page or a section of your web or mobile property. Read more about Content Types.

    For this website, two basic content types are required: News and Category. For quick integration, we have already created these content types. You simply need to import them to your stack. (You can also create your own content types. Learn how to do this).

    To import the content types, first, save the zipped folder of the JSON files given below on your local machine. Extract the files from the folder. Then, go to your stack in Contentstack. The next screen prompts you to either create a new content type or import one into your stack. Click the “Import” link, and select the JSON file saved on your machine.

    Note: Import JSON files in the sequence: “category.json” and “news.json”

    Here’s a brief overview of all the content types required for this project.

      • News: This content type lets you add the news content into your app.
      • Category: This content type lets you create the various categories of your news app.

    Download All Content Types
    Now that all the content types are ready, let’s add some content for your website.

  4. Adding content

    Create and publish entries for the “News” and “Category” content types

    Add a few dummy entries for news articles in the “News” and “Category”content types. Save and publish these entries. Learn how to create and publish entries.

    With this step, you have created sample data for your website. Now, it’s time to use and configure the presentation layer.

  5. Create React Typescript project

    Now create a React app and integrate it with Typescript. Run the following commands to initiate the project:

    # Make a new directory
    $ mkdir react-typescript-news
    
    # Change to this directory within the terminal
    $ cd react-typescript-news
    
    # Initialise a new npm project with defaults
    $ npm init -y
    
    # Install React dependencies
    $ npm install react react-dom
    
    # Make index.html and App.tsx in src folder
    $ mkdir src
    $ cd src
    $ touch index.html
    $ touch App.tsx
    
    # Make Home.jsx in pages folder
    $ mkdir pages
    $ cd pages
    $ touch Home.jsx
    $ cd ..
    
    # Open the directory in your favorite editor
    $ code .
    

    Tip: For Windows Users, run this given command in the terminal to install “touch” in your system: npm install -g touch-for-windows

    Paste the below code in the “index.html” file.

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Contentstack + React + TypeScript + News + app</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
      <div id="main"></div>
      <script src="./App.tsx"></script>
    </body>
    </html>

    You can code your CSS file and save it according to this path: “/src/styles/styles.css”

    After adding the relevant files, the project’s file directory will look as shown in the image below:

    folder_structure

    Run the following command in the terminal to install TypeScript and Parcel (an application bundler) in our app.

    # Install Parcel to our DevDependencies
    $ npm i parcel-bundler -D
    
    # Install TypeScript
    $ npm i typescript -D
    
    # Install types for React and ReactDOM
    $ npm i -D @types/react @types/react-dom

    Update the package.json file with the below code to start the development server.

    "scripts": {
        "dev": "parcel src/index.html"
      }
  6. Initialize Contentstack’s JavaScript Delivery SDK

    We will use Contentstack’s JavaScript Delivery SDK in this app. You can either download the SDK or install it by running the below command in the terminal:

    # Install Contentstack dependencies
    $ npm install contentstack

    Place the following code in the Home.jsx file, and populate it with the tokens and environment’s name to fetch the content from Contentstack.

    Additional Resource: You can refer the Authentication guide in order to learn to find your Stack’s API key and Delivery Token.

    import Contentstack from 'contentstack'
    import React, {Component} from 'react'
    import '../styles/styles.css'
    
    
    // Initialize Contentstack
    const Stack = Contentstack.Stack('<stack_api_key>', '<stack_delivery_token>', '<environment_name>')
    
    export default class Home extends Component{
        constructor() {
          super()
          this.state = { loading : true, result: null}
        }
        componentDidMount () {
          var  Query = Stack.ContentType("news").Query()
          .toJSON()
          .find()
          .then((result) => {
            this.setState({loading : false, result:result})
          })
          .catch((error) => {
            console.log(error)
          })
        }
      
        renderList (post) {
          return (
            <main>
            <div classname="media-body ">
              {
                post.map((value, index) => {
                  return (
                  <article classname="content-section">
                     <div classname="article-metadata">
                       <h3 classname="article-title">{ value.title }</h3>
                       <div dangerouslySetInnerHTML={{ __html: value.body} } />
                     </div>
                </article>
                     )
                })
              }
            </div>
            </main>
          )
        }
      
        render () {
          const {loading, result} = this.state
          return (this.state.loading) ? <h1>loading...</h1> : this.renderList(result[0])
        }
      }

    Additional Resource: Refer the JavaScript Delivery SDK Queries section to learn more about the queries that are used to fetch content from Contentstack.

    Add the below code in the App.tsx file to load the Homepage of the website.

    import * as React from 'react';
    import { render } from 'react-dom';
    import Home from './pages/Home';
    
    render(<Home/>, document.getElementById('main'));
  7. Build and configure website

    Once the code is ready, run this command to view the app:

     $ npm run dev

    This command will open the app at “http://localhost:1234”.

    To get your app up and running quickly, we have already created a sample website (using contentstack-react-ts-news-webapp) for this project. You simply need to download it and change the configuration.

    Download code

Additional Resource: You can also use Contentstack with React Native to build a news app for iOS or Android. Refer our guide on how to create a news app for iOS and/or Android using React Native and Contentstack.

Was this article helpful?

Thanks for your feedbackSmile-icon

On This Page

^