React (Typescript)

Rollbar SDK for Typescript applications

NOTE: As of April 2021, Rollbar has a new React library for React JS and React Native. Use the instructions found here to implement the newer library. This new library does not yet support Typescript.

Rollbar.js supports React applications with no additional configuration required. For apps using React 15.2 and later, production error messages are automatically decoded.

Please see the documentation here on getting set up with rollbar.js.

Create React App

The easiest way to integrate with an app managed via create-react-app is to place our snippet from here in your public/index.html file. Setting the captureUncaught option to true will result in reporting all uncaught exceptions to Rollbar by default.

It is possible to enable reporting only in production by setting enabled conditionally:

// Some versions of create-react-app won't interpolate `%NODE_ENV%` inside the `_rollbarConfig` object.
const nodeEnv = '%NODE_ENV%';
_rollbarConfig = {
  enabled: (nodeEnv === 'production'),
  // ...
}

See the section on environment variables in the create-react-app documentation.

Using Rollbar in React Components

Install using the node package manager, npm:

npm install --save rollbar

The following example shows how to integrate rollbar.js in your React app. All Rollbar capabilities can be used by your React Components, and when the captureUncaught option is set in your Rollbar config, all uncaught exceptions will be reported.

This method and the snippet described above should typically not be used at the same time. Pick one method that best suits your needs.

import React from "react";
import ReactDOM from "react-dom";
import Rollbar from "rollbar";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      rollbar: new Rollbar({
        accessToken: 'POST_CLIENT_ITEM_TOKEN',
        captureUncaught: true,
        captureUnhandledRejections: true,
      })
    };

    this.logInfo = this.logInfo.bind(this);
    this.throwError = this.throwError.bind(this);
  }

  logInfo() {
    // Example log event using the rollbar object.
    this.state.rollbar.info('react test log');
  }

  throwError() {
    // Example error, which will be reported to rollbar.
    throw new Error('react test error');
  }

  render() {
    return (
      <React.Fragment>
        <h1>Rollbar Example for React</h1>
        <button id='rollbar-info' onClick={ this.logInfo }>Log Info</button>
        <button id='throw-error' onClick={ this.throwError }>ThrowError</button>
      </React.Fragment>
    );
  }
}

The rollbar object can be passed as a prop to other components as needed.

📘

For help with importing or requiring Rollbar into your project with Typescript or a version of ECMAScript (ES5/ES6/ES7/ES8/ES9), please see this document here

📘

For more information on rollbar.js, please see the docs here.


Did this page help you?