Track events in Reactjs pages and components globally

690 Views Asked by At

I need to listen to following events and do action accordingly

  1. Form submit event - if the form submission is successful, I need to broadcast success event Added Name Record and submit the data along with it to 3rd party service. If not, I need to broadcast a failed event say Name submission failed along with where the error occurred.

  2. Page visit/Route Change - Self explanatory

  3. Click events - Can be from list item click and button click. In case of list item need to pass item details and in case of button just the name maybe

  4. Searches - Any searches made should fire the event sending the keyword.

I am using React - 0.13 and Reflux store.

How can I approach towards it to handle the events at a global level and without writing code at each button click/submit event/search etc ?

What is the best approach ? Body handler won't be enough I feel for this level of customisation required!

P.S - When I say broadcast let's assume that I have a 3rd party function call to make instead.

1

There are 1 best solutions below

3
Robert Farley On

Purely React ways:

Create base components to globally handle events with extensible event handling methods:

const MyForm = ({ onSubmit, children, ...props }) => (
  <form {...props} onSubmit={evt => {
    // do global handling
    onSubmit(evt);
  }}>
    {children}
  </form>
);

//use case
const CustomForm = () => (
  <MyForm onSubmit={evt => /* custom handling */}>
    {/* CustomForm inputs and such */}
  </MyForm>
)

Alternatively, you could take the HOC approach and wrap each handler you need:

const MyFormHOC = FormComponent => {
  return class extends React.Component {
    render() {
      const { onSubmit, ...props } = this.props;
      return (
        <FormComponent {...props} onSubmit={evt => {
          // do global handling
          onSubmit(evt);
        }}/>
    }
  }
};

//use case
let CustomForm = ({ onSubmit, ...props }) => (
  <form onSubmit={evt => onSubmit(evt)}>
    {/* CustomForm inputs and such */}
  </form>
);
CustomForm = MyForm(CustomForm);

Downside to HOC approach is that your components need to pass along the event handler to the DOM element that will ultimately call it.

You could go one step further and create a single base component or HOC that handles all of your global events and then start using that as needed on your other components. It would need to know which props are supported by what components, though (e.g., onSubmit doesn't belong on anything besides a form).