React

To use Sentry with your React application, you will need to use @sentry/browser (Sentry’s browser JavaScript SDK).

Add the Sentry SDK as a dependency using yarn or npm:

# Using yarn
$ yarn add @sentry/browser

# Using npm
$ npm install @sentry/browser

You can also use our more convenient CDN version.

Connecting the SDK to Sentry

After you’ve completed setting up a project in Sentry, Sentry will give you a value which we call a DSN or Data Source Name. It looks a lot like a standard URL, but it’s just a representation of the configuration required by the Sentry SDKs. It consists of a few pieces, including the protocol, public key, the server address, and the project identifier.

You should init the Sentry browser SDK as soon as possible during your application load up, before initializing React:

import React from 'react';
import ReactDOM from 'react-dom';
import * as Sentry from '@sentry/browser';
import App from 'src/App';

Sentry.init({dsn: "___PUBLIC_DSN___"});

ReactDOM.render(<App />, document.getElementById('root'));

On its own, @sentry/browser will report any uncaught exceptions triggered from your application.

You can trigger your first event from your development environment by raising an exception somewhere within your application. An example of this would be rendering a button:

return <button onClick={methodDoesNotExist}>Break the world</button>;

Error Boundaries

If you’re using React 16 or above, Error Boundaries are an important tool for defining the behavior of your application in the face of errors. Be sure to send errors they catch to Sentry using Sentry.captureException. This is also a great opportunity to collect user feedback by using Sentry.showReportDialog.

import React, { Component } from 'react';
import * as Sentry from '@sentry/browser';

class ExampleBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { eventId: null };
    }

    static getDerivedStateFromError(error) {
      return { hasError: true };
    }

    componentDidCatch(error, errorInfo) {
      Sentry.withScope((scope) => {
          scope.setExtras(errorInfo);
          const eventId = Sentry.captureException(error);
          this.setState({eventId});
      });
    }

    render() {
        if (this.state.hasError) {
            //render fallback UI
            return (
              <button onClick={() => Sentry.showReportDialog({ eventId: this.state.eventId })}>Report feedback</button>
            );
        }

        //when there's not an error, render children untouched
        return this.props.children;
    }
}

export default ExampleBoundary