Start typing to search...

The @withkoji/core package

In the previous topic of this tutorial, you created a new project by forking an existing one, made minor edits, and then published your new app. In this topic, you will continue using the code editor to install and use the @withkoji/core package.

You will learn how to:

  • Use the terminal feature inside the code editor to run commands.

  • Install and import the @withkoji/core package into your project.

  • Use the @withkoji/core package to capture input from a user.

The JavaScript ecosystem

JavaScript has become the most popular language used in developing web applications. Therefore, Koji features and tools for developers are built with and for JavaScript and its surrounding ecosystem.

This support means that you can develop Koji apps using popular JavaScript frameworks, such as React, Vue, and Svelte. It also means that you have access to NPM, the world’s largest software registry with over 1.5 million packages that you can install and use in your project.

This tutorial focuses on the primary Koji package @withkoji/core, which exposes many of Koji’s powerful platform features through easy-to-use modules and methods.

Installing a package

You can send text-based commands to the Koji platform using the code editor’s built-in terminal or command-line interface (CLI).

By default, the terminal pane is minimized at the bottom of the code editor.

  • To expand the terminal pane, click any of the existing terminal tabs or the chevron (chevron icon) at the rightmost end of the pane.

  • To minimize the terminal pane, click the active tab or the chevron.

You use this terminal to install the @withkoji/core package and to stop and start the service that allows you to preview your app.

Exercise 2.1: Install @withkoji/core

  1. Open your project in the code editor.

    1. Go to your Developer Portal page and click your project.

    2. In the Project Details page, click Open in Code Editor.

  2. At the bottom of the code editor, click the frontend tab of the terminal pane.

    By default, the messages would indicate that the project compiled successfully.

  3. Stop the running service.

    1. Click inside the terminal.

    2. Press Ctrl+C or Cmd+C.

  4. Install @withkoji/core.

    npm install @withkoji/core

    NPM displays the status as it requests the latest package details and installs the package in the project.

  5. Restart the service.

    npm start

    This triggers React to recompile your project and then start the service. The terminal will display the same messages as it did before you stopped the process.

  6. Minimize the terminal pane.

Note
If you add a backend to your app, you must also install the package in the backend tab. This tutorial does not include a backend component.

Importing the package

After installation, you must import the package in your project.

The scaffold that you forked for this tutorial was designed for React. With React, you need only one line of code to import the package.

Exercise 2.2: Import the package and read the app’s initial settings

  1. From the navigation pane, open the file /frontend/src/index.js.

  2. Modify the file to look as follows:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import Koji from '@withkoji/core';  // (1)
    import kojiConfig from '../../koji.json';  // (2)
    import './index.css';
    import App from './App';
    
    Koji.config(kojiConfig, {  // (3)
      projectId: process.env.REACT_APP_PROJECT_ID,
      services: {
        frontend: process.env.REACT_APP_FRONTEND_URL,
      },
    });
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    1. Imports Koji, which is the default object exported by the @withkoji/core package.

    2. Imports the koji.json file as kojiConfig. This file contains the initial settings of your app.

    3. Calls Koji.config with the kojiConfig object and other parameters to provide your app’s initial settings to the package.

    Note
    By calling Koji.config outside of React’s render loop, it is called exactly once, when the application initially loads. Calling Koji.config multiple times throws an error.
  3. Click Save or press Ctrl+S or Cmd+S.

Now, you are ready to use the modules and methods from the @withkoji/core package.

About the React state

In React, state holds the set of information that your app needs while running.

Most web applications use state to hold metadata, such as whether the user selected light or dark mode, whether a section of content is expanded or collapsed, or whether the user is logged in or not.

In this tutorial, you will use state to store the URL of the rotating image.

Exercise 2.3: Store the image URL in state

  1. From the navigation pane, open the file /frontend/src/App.js.

  2. Modify the file to look as follows:

    // (1)
    import { useState } from 'react';  // (2)
    import './App.css';
    
    function App() {
      const [logoSrc, setLogoSrc] = useState('https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg');  // (3)
      return (
        <div className="App">
          <header className="App-header">
            <img src={logoSrc} className="App-logo" alt="logo" />  // (4)
            <p>Having Fun with Koji</p>
          </header>
        </div>
      );
    }
    
    export default App;
    1. Removed the statement that imported the local logo.svg file.

    2. Imports useState from react, which is a React hook that allows you to manage the state inside the component.

    3. Calls the useState hook to initialize logoSrc with the React logo from Wikimedia Commons.

    4. Uses the new const logoSrc as the source of the image, instead of the previously imported logo.

  3. Click Save or press Ctrl+S or Cmd+S.

The syntax for the useState hook is as follows:

const [myValue, functionToSetMyValue] = useState(initialValue);

where the reactive variable myValue is initialized with initialValue and can be updated using functionToSetMyValue.

This allows you to easily replace the image by calling setLogoSrc to change the value of logoSrc.

Capturing user input with @withkoji/core

The Koji platform exposes a number of methods to capture different types of dynamic user inputs. One of these methods is Koji.ui.capture.image, which allows a user to select or upload an image.

Exercise 2.4: Enable image selection or upload

  1. Modify App.js to look as follows:

    import Koji from '@withkoji/core';  // (1)
    import { useState } from 'react';
    import './App.css';
    
    function App() {
      const [logoSrc, setLogoSrc] = useState('https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg');
    
      const captureImage = async () => {  // (3)
        const src = await Koji.ui.capture.image();
        if (src) {  // (4)
          setLogoSrc(() => src);
        }
      };
    
      Koji.ready();  // (5)
    
      return (
        <div className="App">
          <header className="App-header">
            <img src={logoSrc} className="App-logo" alt="logo" />
            <p>Having Fun with Koji</p>
            <button onClick={captureImage}>Capture Image</button>  // (2)
          </header>
        </div>
      );
    }
    
    export default App;
    1. Imports Koji, which is the default object exported by the @withkoji/core package.

    2. Adds a button which calls the captureImage function when clicked.

    3. The captureImage function uses the Koji.ui.capture.image method to request user input.

    4. If a value is returned, setLogoSrc is called, and the state is updated.

    5. Indicates that the app is ready to receive events.

  2. Click Save or press Ctrl+S or Cmd+S.

  3. In the preview pane, click the refresh icon (refresh icon).

  4. Click Capture Image.

    Clicking the button triggers the captureImage function which calls the Koji.ui.capture.image method which displays a user-input control.

    The user-input control displays a menu for the user to select an image in any of the following ways:

    • By uploading an image file.

    • By specifying a URL where an image file can be imported from.

    • By browsing and selecting from Koji’s extensive asset packs.

  5. Select or upload an image.

    The uploaded or selected image is stored in Koji’s content delivery network (CDN).

    The preview pane is automatically updated to display the new image.

The Koji.ui.capture.image method returns the image’s Koji URL; however, the URL is not saved permanently. When you switch to a different tab or refresh the app, the default image is displayed again.

Additional processing for images and videos

You can perform additional processing to images and videos after the user uploads them either directly from their own local directories or from a URL.

For example, your app can automatically blur any uploaded image.

Exercise 2.5: Blur an uploaded image

  1. In the file /frontend/src/App.js, add a parameter to Koji.ui.capture.image to blur the uploaded image.

    1. Search for the following line:

      const src = await Koji.ui.capture.image();

    2. Replace it with:

      const src = await Koji.ui.capture.image({ blur: 10 });

  2. Click Save or press Ctrl+S or Cmd+S.

  3. Click Capture Image in the preview again.

  4. Upload a new image file or enter a URL where an image can be imported from.

    Important
    Post-processing has no effect on images selected from image packs.

    The preview pane displays a blurred image.

  5. (Optional) Set blur to 50, save, and upload the image again.

Note
The image itself is transformed before it is stored; the effect is not produced by CSS or any other styling. The original unblurred image is not saved.

Republishing

Republish your app to make your changes available in your app’s permanent URL.

Exercise 2.6: Republish

  1. Verify that all changes have been saved in all open tabs in the editing pane.

  2. From the navigation pane, click Publish Now.

  3. Verify that /frontend/src/index.js and /frontend/src/App.js are listed in the Changes section.

    Note
    Because you installed @withkoji/core, package.json and package-lock.json were automatically updated with the installed @withkoji/core version.
  4. Click Publish New Version.

  5. After your app is published successfully, click Back to Overview to return to the Project Details page.

    Notice the new version in the Deployment Status card and the additional line in the Development Status card.

  6. Click the View Published Koji card and test your updated app.

What’s next

You should now be familiar with using the terminal to make command-line changes to your project, as well as installing and importing the @withkoji/core package. You also learned how to capture an image from a user and how to manage state in React.

In the next topic, you will enable customization by implementing the Remix context. Customization allows users to create and publish customized versions of your app without coding.