Show an interactive weight goal chart in a paywall

Follow this recipe to display the projected weight of each user as a chart in a paywall flow. The user enters their current and goal weight in an onboarding flow. Your app collects both values. The chart shows the weekly progress that the user can expect with your app, from one value to the other. Your app renders the chart as a native view in a custom element. On iOS, the view uses Swift Charts. On Android, the view draws the chart without a chart library.

Before you start

  • Update your app to Adapty React Native SDK 4.4 or later. Earlier SDK versions show the fallback content for every custom element.
  • Set up your app to fetch and display flows.
  • Set up the native code of your app for custom elements, as in the React Native guide.
  • On iOS, the drag along the chart needs iOS 17 or later. On iOS 16, users see the line, but can’t drag along it.
  • On Android, set up Jetpack Compose in your app module. The chart in this recipe is a composable. Add Compose Foundation to your app with Gradle, from androidx.compose.foundation:foundation.

Create two separate flows — one for the onboarding, and one for the paywall. Add each to a placement. The code in this recipe fetches the paywall flow from the placement with the ID weight_paywall.

1. Ask for the current and goal weight in the onboarding flow

In the Flow & Paywall Builder, add two Number inputs to the onboarding flow:

  • One for the current weight in kilograms, with the Element ID weight.
  • One for the goal weight in kilograms, with the Element ID goal_weight.

To make your app read the weights the same way in every locale, select Integer from the Format dropdown of both inputs. An input sends its value to your app as text, exactly as the user types it. The code in this recipe reads “70.5” and “70,5” differently. Whole numbers have no decimal separator.

To make sure that your app receives both values, end the onboarding flow with a screen that has no inputs. On that screen, add a button with the Close flow action. Inputs send their values when they lose focus or when the user moves to another screen.

2. Add the custom element to the paywall screen

In the paywall flow, add a custom element to a screen, and set it up for the chart:

  • Type: line_chart.
  • ID: weight_goal.
  • Height: Keep the default Fixed height. The chart fills the custom element.

Keep the custom element out of containers that respond to touch, such as a carousel, so that only the chart responds to a drag along it.

Inside the custom element, add an Image with a sample weight chart. Users see it as the fallback when their version of your app doesn’t display the chart.

3. Save the current and goal weight in your app

Collect the current and goal weight from the flow_user_input events of the onboarding flow, as in Process data from flows. To know that the user reached the last screen, watch for a flow_screen_showed event with is_last_screen set to true. When the onboarding flow closes after that screen, pass both weights to showWeightPaywall, the function that opens the paywall flow with the chart.

The following function returns the onAnalytics and onDisappeared handlers of the onboarding flow:

import type { FlowEventHandlers } from 'react-native-adapty';
import { showWeightPaywall } from './showWeightPaywall';

// the event handlers of the onboarding flow view
export function weightOnboardingHandlers(): Partial<FlowEventHandlers> {
  const enteredWeights: Record<string, string> = {};
  let reachedLastScreen = false;

  return {
    onAnalytics(name, params) {
      if (name === 'flow_screen_showed' && params.is_last_screen === true) {
        reachedLastScreen = true;
      } else if (
        name === 'flow_user_input' &&
        typeof params.element_id === 'string' &&
        typeof params.value === 'string'
      ) {
        enteredWeights[params.element_id] = params.value;
      }
      return false; // keep the flow open
    },
    onDisappeared() {
      // number inputs send their values as strings
      const currentWeight = Number.parseFloat(enteredWeights.weight ?? '');
      const goalWeight = Number.parseFloat(enteredWeights.goal_weight ?? '');
      if (reachedLastScreen && !Number.isNaN(currentWeight) && !Number.isNaN(goalWeight)) {
        showWeightPaywall(currentWeight, goalWeight);
      }
      return false;
    },
  };
}

Before you present the onboarding flow, pass the handlers to its view:

const view = await createFlowView(flow);
view.setEventHandlers(weightOnboardingHandlers());
await view.present();

If your app already sets onAnalytics or onDisappeared for the onboarding flow, add the code of weightOnboardingHandlers to your handlers. Each handler that you pass to setEventHandlers replaces any earlier handler that has the same name.

4. Create the chart view

Create a model of a weight plan, and a view with the chart. The plan has one entry per week, from the current weight to the goal weight. When the user drags along the chart, the view marks the week at the touch point, and displays the projected weight for that week:

The plan assumes that the weight changes by 0.5 kg per week. To use another rate, edit weeklyChange.

5. Match the chart to the custom element

In your app-wide resolver, add a WeightPlanStore property. Then return the chart view for the line_chart Type and the weight_goal ID. The highlighted lines show what to add or change. If your app has no app-wide resolver yet, copy the whole code:

Until your JavaScript code sends the weights to your native code, the resolver returns no view, and users see the fallback.

6. Send the weights from your JavaScript code

Set the resolver at app launch, and fill the store from your JavaScript code through a Turbo Native Module. The module has a JavaScript spec and an implementation for each platform.

In a specs folder at the root of your project, create the spec of the module:

import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  setWeights(currentWeight: number, goalWeight: number): void;
}

export default TurboModuleRegistry.getEnforcing<Spec>('NativeWeightPlanStore');

To generate the native code of the spec, add codegenConfig to package.json. Replace com.example.app with the package name of your Android app, in package.json and in the Kotlin implementation of the module. If package.json already has codegenConfig, only add NativeWeightPlanStore to the modulesProvider object:

"codegenConfig": {
  "name": "AppSpecs",
  "type": "modules",
  "jsSrcsDir": "specs",
  "android": {
    "javaPackageName": "com.example.app.specs"
  },
  "ios": {
    "modulesProvider": {
      "NativeWeightPlanStore": "RCTNativeWeightPlanStore"
    }
  }
}

Implement the module for each platform:

In your JavaScript code, send the weights to the store before the paywall flow opens:

import { adapty, createFlowView } from 'react-native-adapty';
import NativeWeightPlanStore from './specs/NativeWeightPlanStore';

export async function showWeightPaywall(currentWeight: number, goalWeight: number) {
  try {
    // the native resolver builds the chart from these weights
    NativeWeightPlanStore.setWeights(currentWeight, goalWeight);
    const flow = await adapty.getFlow('weight_paywall');
    const view = await createFlowView(flow);
    await view.present();
  } catch (error) {
    // handle the error
  }
}

7. Test on a device

The Flow & Paywall Builder can’t run your app code, so its canvas only shows the fallback. To preview the chart:

  1. Publish both flows. To see the latest published versions instead of cached ones, register the device as a test device.
  2. Run a build of your app that includes the resolver. On iOS, use a device with iOS 17 or later. Complete the onboarding flow with a current and a goal weight. Verify that the line of the chart starts at the current weight and ends at the goal weight.
  3. Drag along the chart, and verify that the projected weight for the week under your finger appears above the line.

To test the fallback, return no view for the line_chart Type, and open the paywall flow again.

To find out why the fallback appears instead of the chart, follow the instructions in the Test on a device section of the React Native guide.