@amplitude/react-amplitude

中文文档
1.0.1-beta.1发布于 2023/01/18MITESM + CJS近 30 天下载 4738

A React component library for easy product analytics instrumentation

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录15 节
  1. Project Status
  2. The problems with traditional, imperative event-based loggi…
  3. The problems with "autotrack" solutions
  4. The solution
  5. Example: Instrumenting Tic-Tac-Toe (From Facebook's Intro t…
  6. Installation
  7. API
  8. AmplitudeProvider props
  9. Amplitude props
  10. LogOnMount props
  11. instanceName
  12. LogOnChange props
  13. instanceName
  14. License
  15. Friends & Related Projects

react-amplitude

Travis npm

A React component library for easy product analytics instrumentation.

Project Status

react-amplitude is not an officially supported Amplitude SDK or library, and deprecated now.

Please use our offical Typescript SDK to track with React!

The problems with traditional, imperative event-based logging

  • Contextual event information (i.e. "event properties") often require lots of plumbing to the code path where the events are logged, requiring more code and breaking encapsulation.
  • Similarly, it can be difficult to provide contextual information to events fired in low-level, reusable components (e.g. Buttons, Dropdowns, Links, etc.).
  • Traditional event-based analytics logging often use imperative APIs, which can sometimes require more code and be more painful when writing declarative React components.

The problems with "autotrack" solutions

  • Autotrack solutions can be unreliable, as they may depend on attributes that engineers may unintentionally change (like CSS selectors).
  • Autotrack solutions may unintentionally track sensitive user data.
  • Autotrack can't capture all kinds of events, so you may end up requiring to implement manual event logging.

The solution

react-amplitude has a modern, declarative API to make it easy to instrument new events and properties with Amplitude. It takes advantage of core React features to propagate contextual information down through the component hierarchy. This makes it far less painful to add new event properties to existing events.

Unlike "autotrack" solutions, react-amplitude does require some code changes in order to start sending data to Amplitude. However, it aims to minimize the amount of code required to start collecting data and make instrumentation seem less like a chore.

If you use common reusable components in your React application like Buttons, Dropdowns, Links, etc., you should be able to achieve "autotrack"-like instrumentation with just a few lines of code. And from there, it can be really simple to instrument new properties and context throughout your application, giving you the same flexibility as manual event logging.

Example: Instrumenting Tic-Tac-Toe (From Facebook's Intro to React Tutorial)

Events logged:

  • start game
  • game won
  • click square
  • jump to move
  • go to game start

Event properties:

  • scope (array; "square", "history", "game")
  • moves made (number)
  • winner ("X" or "O")
  • current player ("X" or "O")
import React from "react";
import { render } from "react-dom";
import amplitude from "amplitude-js";
import {
  AmplitudeProvider,
  Amplitude,
  LogOnMount
} from "@amplitude/react-amplitude";

const AMPLITUDE_KEY = "";

function Square(props) {
  return (
    <Amplitude
      eventProperties={inheritedProps => ({
        ...inheritedProps,
        scope: [...inheritedProps.scope, "square"]
      })}
    >
      {({ instrument }) => (
        <button
          className="square"
          onClick={instrument("click square", props.onClick)}
        >
          {props.value}
        </button>
      )}
    </Amplitude>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    };
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
        {
          squares: squares
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const desc = move ? "Go to move #" + move : "Go to game start";
      return (
        <li key={move}>
          <Amplitude
            eventProperties={inheritedProps => ({
              ...inheritedProps,
              scope: [...inheritedProps.scope, "move button"]
            })}
          >
            {({ logEvent }) => (
              <button
                onClick={() => {
                  logEvent(move ? "jump to move" : "go to game start");
                  this.jumpTo(move);
                }}
              >
                {desc}
              </button>
            )}
          </Amplitude>
        </li>
      );
    });

    let status;
    if (winner) {
      status = "Winner: " + winner;
    } else {
      status = "Current player: " + (this.state.xIsNext ? "X" : "O");
    }

    return (
      <AmplitudeProvider
        amplitudeInstance={amplitude.getInstance()}
        apiKey={AMPLITUDE_KEY}
      >
        <Amplitude
          eventProperties={{
            scope: ["game"],
            "moves made": this.state.step,
            "current player": this.state.xIsNext ? "X" : "O",
            winner
          }}
        >
          <LogOnMount eventType="start game" />
          {!!winner && <LogOnMount eventType="game won" />}
          <div className="game">
            <div className="game-board">
              <Board
                squares={current.squares}
                onClick={i => this.handleClick(i)}
              />
            </div>
            <Amplitude
              eventProperties={inheritedProps => ({
                ...inheritedProps,
                scope: [...inheritedProps.scope, "history"]
              })}
            >
              <div className="game-info">
                <div>{status}</div>
                <ol>{moves}</ol>
              </div>
            </Amplitude>
          </div>
        </Amplitude>
      </AmplitudeProvider>
    );
  }
}

// ========================================

render(<Game />, document.getElementById("root"));

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

Edit nnowj5nonj

Installation

With npm:

npm install --save @amplitude/react-amplitude

With yarn:

yarn add @amplitude/react-amplitude

react-amplitude does not come with its own copy of the Amplitude JavaScript SDK. You can either install the Amplitude SDK via npm or with a JavaScript snippet.

API

AmplitudeProvider props

amplitudeInstance

A required prop. You should be providing an Amplitude instance returned from the Amplitude JS SDK's getInstance method.

apiKey

An optional prop that can be used to initialize the Amplitude instance with the provided key.

userId

An optional prop that can be used to attribute all events to a specific user.

Amplitude props

children

If can pass a function as the children prop, it will be called with a single object parameter, and the return value of that function will be used for rendering the actual React subtree.

The single object parameter has two useful fields: logEvent and instrument.

logEvent is a function that can be used to imperatively log events. All event properties from this component's eventProperties prop and any inherited properties will be included in these events.

Example:

function Button(props) {
  return (
    <Amplitude>
      {({ logEvent }) =>
        <button
          onClick={() => {
            logEvent('button click');
            props.onClick();
          }}
        >
          {props.children}
        </button>
      }
    </Amplitude>
  )
}

instrument is a function that can be used to declaratively log events. If you have pre-existing event handlers, just wrap the functions with an instrument, and events will fire every time your normal event handlers are executed. instrument takes two parameters, the event type and the function to proxy.

instrument is also useful if you would like to prevent re-rendering via shouldComponentUpdate optimizations like PureComponent. It memoizes its arguments and returns the same function instance across re-renders. For this reason, it's not recommended to use instrument for functions that change on every render (i.e. inlined or "arrow" functions in render).

Example:

function Button(props) {
  return (
    <Amplitude>
      {({ instrument }) =>
        <button
          onClick={instrument('button click', props.onClick)}
        >
          {props.children}
        </button>
      }
    </Amplitude>
  )
}

eventProperties

If an object is provided, the object will be merged with event properties higher-up in the component hierarchy and included in all events logged in this component or any components in its subtree.

If a function is provided, it will be called with a single parameter, inheritedProperties, that contains all of the event properties from components higher in the React component hierarchy. The return value from this function will be used for all logged events in this component or other components in its subtree.

debounceInterval

If provided, events logged by the component will be debounced by this amount, in milliseconds.

userProperties

An optional object that if provided, will trigger updates to the current user's "user properties."

LogOnMount props

eventType

When this component mounts, it will log an event with this value as the event type.

eventProperties

These properties will be applied to the event when the component mounts.

instanceName

THe Amplitude instance to log events to.

LogOnChange props

value

Required prop, that when changes (diffing is done with shallow equality comparison), logs an event.

eventType

When the value prop changes, it will log an event with this value as the event type.

eventProperties

These properties will be applied to the event when the component mounts.

instanceName

The Amplitude instance to log events to.

License

MIT

  • analytics-react: Write analytics code once with Segment and collect customer data from any source and send it to over 250+ destinations.

版本与发布记录

@amplitude/react-amplitude 共发布 20 个版本,首次发布于 2018/01/07;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.1-beta.1latest2023/01/183 年前
1.0.1-beta.0beta2019/06/257 年前
1.0.02018/10/168 年前
1.0.0-beta.6next2018/05/158 年前
1.0.0-beta.52018/05/158 年前
1.0.0-beta.42018/03/208 年前

关于 @amplitude/react-amplitude 的常见问题

@amplitude/react-amplitude 是什么?

A React component library for easy product analytics instrumentation注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @amplitude/react-amplitude?

在项目目录运行 npm install @amplitude/react-amplitude,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^0.14.0 || ^15.0.0-0 || ^16.0.0-rc || ^17.0.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@amplitude/react-amplitude 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/amplitude__react-amplitude 是否存在。

@amplitude/react-amplitude 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@amplitude/react-amplitude 可以商用吗?

@amplitude/react-amplitude 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@amplitude/react-amplitude 的下载量有多少?

根据 npm 官方下载统计,@amplitude/react-amplitude 在 2026/10/06 – 2026/11/04 这 30 天内被下载 4,738 次,日均约 158 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@amplitude/react-amplitude 还在维护吗?

最新版本 1.0.1-beta.1 发布于 2023/01/18(3 年前);至今共发布 20 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/01/07。作者已将其标记为弃用,新项目建议寻找替代方案。