React integrationedit

This document covers how to use Real User Monitoring JavaScript agent with React applications. Please see our Getting started guide for configuring the Real User Monitoring agent.

Installing Elastic APM React packageedit

Install the @elastic/apm-rum-react package as a dependency to your application:

npm install @elastic/apm-rum-react --save

Instrumenting your React applicationedit

The React integration package provides two approaches to instrumenting your application:

Instrumenting application routesedit

To instrument the application routes, you can use ApmRoute component provided in the package. ApmRoute creates a transaction that has the path of the Route as its name and has route-change as its type.

Currently ApmRoute only supports applications using react-router library.

First you should import ApmRoute from the @elastic/apm-rum-react package:

import { ApmRoute } from '@elastic/apm-rum-react'

Then, you should replace Route components from the react-router library with ApmRoute. You can use ApmRoute in any of the routes that you would like to monitor, therefore, you don’t have to change all of your routes:

class App extends React.Component {
  render() {
    return (
      <div>
        <ApmRoute
          exact
          path="/"
          component={() => (
            <Redirect
              to={{
                pathname: '/home'
              }}
            />
          )}
        />
        <ApmRoute path="/home" component={HomeComponent} />
        <Route path="/about" component={AboutComponent} />
      </div>
    )
  }
}

ApmRoute only instruments the route if component property is provided, in other cases, e.g. using render or children properties, ApmRoute will only renders the route without instrumenting it, please instrument the individual component using withTransaction in these cases instead.

Instrumenting individual React componentsedit

First you should import withTransaction from the @elastic/apm-rum-react package:

import { withTransaction } from '@elastic/apm-rum-react'

Then, you can use withTransaction as a function to wrap your React components:

class AboutComponent extends React.Component { }
export default withTransaction('AboutComponent', 'component')(AboutComponent)

withTransaction accepts two parameters, "transaction name" and "transaction type". If these parameters are not provided, the defaults documented in Transaction API will be used.