Show or hide content in the Oracle JET virtual DOM app

Introduction

Oracle JavaScript Extension Toolkit (Oracle JET) includes a ResponsiveUtils module that contains utilities for working with responsive screen widths and ranges. For example, a specific screen width or range is described by a framework query key, which can be passed into the method getFrameworkQuery() to produce a framework media query string.

The Window interface contains the window variable that represents the window in which your virtual DOM app is running. Passing the framework media query into the window.matchmedia() method returns an object with properties that you can use to check whether the screen width of the window in which your virtual DOM app is running matches your specified width or range.

With this object and use of Preact hooks, state, and event listeners, you can monitor the size of the screen your virtual DOM app is running in and responsively display different content when the screen size changes.

Objectives

In this tutorial, you will learn how to use Preact hooks and the Oracle JET ResponsiveUtils module to monitor changes in the size of the window that your virtual DOM app is running in. Then you will adjust the Activity Item Container component of your app to responsively load different content when using medium or smaller screens.

Prerequisites

Task 1: Monitor the Screen Width and Responsively Display Conditional Content

Use Preact hooks and the Oracle JET ResponsiveUtils module to find the browser window’s screen width and monitor when the size changes to medium or smaller. Then use state to keep track of the screen size in the ActivityItemContainer component and render a recolored Activity Item Container with an abbreviated list of items for medium or smaller screens.

  1. Open the Oracle JET Cookbook and navigate to the Cookbook home page. Click Framework in the menu bar, then click Responsive Behaviors, and then click Responsive Loading.

  2. There you can access the API documentation for the ResponsiveUtils namespace. Scroll to the Methods section and read about the getFrameworkQuery method.

  3. Navigate to the JET-Virtual-DOM-app/src/components/ActivityItem directory and open the ActivityItemContainer.tsx file in an editor.

  4. At the top of the file, add import statements for the useRef, useState, and useEffect hooks, as well as the Oracle JET ResponsiveUtils module.

    import { useRef, useState, useEffect } from "preact/hooks";
    import * as ResponsiveUtils from "ojs/ojresponsiveutils";
    
  5. Above the ActivityItemContainer function, add the sm_md_view variable to hold the content that the container will display when the screen is a medium or smaller size, rather than a large or extra-large size.

    // Display this content for medium and narrower screen widths
    const sm_md_view =
      <div id="sm_md" class="oj-flex-item oj-sm-padding-4x-start oj-md-6 oj-sm-12" 
                      style="background-color:lightcyan; padding: 10px; font-size: 10px">
        <h3 id="activityDetailsHeader">Activity Details</h3>
        <div class="item-display no-wrap">
          <ul>
            <li class="li-item">SureCatch Baseball Glove</li>
            <li class="li-item">Western R16 Helmet</li>
            <li class="li-item">Western C1 Helmet</li>
            <li class="li-item">Western Bat</li>
          </ul>
        </div>
      </div>;
    

    Note: As a best practice, we recommend that you define CSS styles in a separate file, not inline as they are here.

  6. Before the return statement of the ActivityItemContainer function, add the following code to make use of the imported Preact hooks and ResponsiveUtils module.

    const ActivityItemContainer = () => {
    
      const mediaQueryRef = useRef<MediaQueryList>(window.matchMedia(ResponsiveUtils.getFrameworkQuery("md-down")!));
    
      const [isSmallMediumWidth, setIsSmallMediumWidth] = useState(mediaQueryRef.current.matches);
    
      useEffect(() => {
        mediaQueryRef.current.addEventListener("change", handleMediaQueryChange);
        return (() => mediaQueryRef.current.removeEventListener("change", handleMediaQueryChange));
      }, [mediaQueryRef]);     
    
  7. Under the useEffect hook, add the following two functions.

    function handleMediaQueryChange(e: MediaQueryListEvent) {
      setIsSmallMediumWidth(e.matches);
    }
    
    function getDisplayType() {
      return (isSmallMediumWidth ? false : true);
    };
    
  8. Finally, modify the ActivityItemContainer function’s return statement to either render the current Activity Items content, if using a large or extra-large screen size, or render the content in the sm_md_view variable, if using a medium or smaller screen size.

    return getDisplayType() ? (
      <div
        id="activityItemsContainer"
        class="oj-flex-item oj-bg-success-20 oj-sm-padding-4x-start oj-md-6 oj-sm-12">
        <div id="container" class="item-display no-wrap">
          <h3>Activity Items</h3>
          <ul>
            <li class="li-item">Louisville Slugger Bat</li>
            <li class="li-item">SureCatch Baseball Glove</li>
            <li class="li-item">Baseball</li>
            <li class="li-item">Western R16 Helmet</li>
            <li class="li-item">Western C1 Helmet</li>
            <li class="li-item">Sure Fire Ball (Set of 4)</li>
          </ul>
        </div>
      </div>
    ) : sm_md_view;
    
  9. Save and close the file.

    Your code should look similar to responsive-screen-activity-items.txt.

Task 2: Run the Virtual DOM App

  1. In the terminal window, change to the JET-Virtual-DOM-app directory and run the virtual DOM app.

    npx ojet serve
    

    Oracle JET tooling runs the virtual DOM app in your local web browser. Viewing the content on a large screen shows the same content as displayed at the end of the previous tutorial.

    The app displayed for a large screen size

    Description of the illustration large_screen_view.png

  2. To display the contents in the sm_md_view variable, drag the edge of the browser window until it is a medium size. In the Activity Item Container, note the abbreviated activity item list under a new Activity Details heading, as well as the container’s new light cyan color.

    The app displayed for a medium screen size

    Description of the illustration medium_screen_view.png

  3. Next, view the virtual DOM app in a small screen size by using Chrome DevTools. Maximize the screen, then right-click the page and select Inspect to bring up the page view in the developer tools.

  4. In the Chrome DevTools toolbar, click Toggle device toolbar button to switch to the device mode.

    Locator for Toggle device toolbar button

    Description of the illustration device_mode_lens.png

  5. Click the Dimensions dropdown menu in the device mode’s screen emulator.

    Various viewports are displayed

    Description of the illustration viewport.png

  6. From the dropdown menu, select a device with a small screen size, such as the Pixel 7, to verify the content changes in the screen emulator.

    The app displayed for a small screen size

    Description of the illustration small_screen_view.png

    In the small screen size, the orientation and layout of the app changes and a shortened list of items is visible under the Activity Details heading. The container is colored light cyan.

  7. In the terminal window, press Ctrl+C, and if prompted, enter y to exit the Oracle JET tooling batch job.

  8. Close the browser window or tab.

  9. Your completed virtual DOM app with responsive design functionality should look similar to jet-virtual-dom-app-responsive-design-final.zip.

Task 3: (Optional) Run a Virtual DOM App from a Restored App

If you want to run the completed Oracle JET virtual DOM app from the supplied code, you can restore the app from the downloaded archive file. To work with a “stripped and zipped” Oracle JET virtual DOM app, you must restore project dependencies, including Oracle JET tooling and the required libraries and modules, within the extracted app.

  1. Download the jet-virtual-dom-app-responsive-design-final.zip file and extract the contents of the completed app to the JET-Virtual-DOM-app folder.

  2. In the terminal window, navigate to the JET-Virtual-DOM-app folder and restore the Oracle JET virtual DOM app by installing the NPM packages that it requires.

    npm install
    
  3. Wait for confirmation.

    Success: Restore complete
    

    The app is ready to run.

  4. Run the app and test it in the browser.

    npx ojet serve
    
  5. Close the browser window or tab that displays your running app.

  6. In the terminal window, press Ctrl+C, and if prompted, enter y to exit the Oracle JET tooling batch job.

Next Step

To proceed to the next tutorial in this learning path, click here.

More Learning Resources

Explore other labs on docs.oracle.com/learn or access more free learning content on the Oracle Learning YouTube channel. Additionally, visit education.oracle.com/learning-explorer to become an Oracle Learning Explorer.

For product documentation, visit Oracle Help Center.