0.3.0 • Published 2 years ago

@microbitsclub/paywall-react v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Microbits Paywall for React

Renders a popup paywall for paywalled microbits content.

Installation

npm install @microbitsclub/paywall-react

Configuration

Get your merchant ID.

Usage

Create a PaywallPopoverConfig instance.

import { stringifyUrl } from '@microbitsclub/paywall-react/dist/src/url';

const paywallPopoverConfig: PaywallPopoverConfig = {
    merchantId: '<your_merchant_id>',

    // Compute the final URL for paywalled content.
    getContentUrl(path, query) {
        return stringifyUrl({
            proto: 'http',
            hostname: 'localhost',
            port: 3000,
            ...path,
            query,
        });
    },
    
    // Compute the final URL for requests to your server. These requests are
    // handled by @microbitsclub/microbits-client request handlers.
    getServerUrl: (path, query) => {
        return stringifyUrl({
            proto: 'http',
            hostname: 'localhost',
            port: 7000,
            ...path,
            query,
        });
    },
};

Wrap your React components with PaywallPopoverProvider wherever a popover paywall should be displayed.

const App: FC<AppProps> = props => {
    return (
        <PaywallPopoverProvider config={paywallPopoverConfig}>
            <StoryList>
                {props.stories.map(({ id, title }) => (
                    <StoryCard key={id} id={id} title={title} />
                ))}
            </StoryList>
        </PaywallPopoverProvider>
    );
}

Intercept link clicks and use the attempNavigateToContent hook API.

const StoryCard: FC<StoryCardProps> = props => {
    const contentUrl = `/story/${props.id}`;
    const popoverPaywall = usePaywallPopover();

    const handleClick = useCallback<MouseEventHandler>(
        e => {
            // Prevent the default action
            e.preventDefault();

            // Handle the attempted navigation
            popoverPaywall.attempNavigateToContent(contentUrl);
        },
        [contentUrl, popoverPaywall]
    );

    return (
        <StoryLinkBox>
            <a href={contentUrl} onClick={handleClick}>{props.title}</a>
        </StoryLinkBox>
    );
}