Wrap a Vanilla JavaScript Package for Use in React

Wrap a Vanilla JavaScript Package for Use in React

In this article, I’ll show you how to wrap a 3rd party widget into a React component using ag-Grid as an example. I’ll show you how we set up the mapping between React Props and the widget’s configuration options. You’ll also learn how to expose a widget’s API through a React component.

Complex web projects often require the use of 3rd party widgets. But what if you’re using a framework while a widget is only available in pure JavaScript?

Table of Contents

  • Understanding the JS Widget: Defining things to bridge
  • What should a wrapper component do?
  • React Wrapper Implementation
  • Synchronizing grid properties updates
  • Exposing API
To use a JavaScript widget in your project, the best approach would be to create a framework specific wrapper. That’s what this article is about.

At ag-Grid we focus on developing the fastest and most feature rich JavaScript data grid for web applications. It has no 3rd party dependencies and is specifically designed to deliver outstanding performance even if being used to display millions of records. To make integrations with React applications easier, we’ve implemented our own React grid wrapper.

Understanding the JS Widget: Defining things to bridge

Most widgets can be configured through configuration options. Usually they also define public API and broadcasts events.

In general, most widgets have:

  • Configuration options
  • A public API
  • Broadcasted events

That’s exactly how you interact with ag-Grid. You can find a good description for the grid’s properties, events, callbacks and API here. In short, the datagrid defines:

  • Grid Properties that enable features of the grid, like row animation.
  • Grid API to interact with the grid at runtime, e.g. to get all the selected rows
  • Grid Events emitted by the grid when certain events happen in the grid, like row sorting or rows selection
  • Grid Callbacks used to supply information from your application to the grid when it needs it, e.g. a callback is called each time a menu is shown that allows your application to customize the menu.

Here’s a very basic pure JavaScript configuration that demonstrates the usage of grid options:

let gridOptions = {
// PROPERTIES - object properties, myRowData and myColDefs are created somewhere in your application
rowData: myRowData,
columnDefs: myColDefs,

// PROPERTIES - simple boolean / string / number properties
pagination: true,
rowSelection: 'single',

// EVENTS - add event callback handlers
onRowClicked: function(event) { console.log('a row was clicked'); },
onColumnResized: function(event) { console.log('a column was resized'); },
onGridReady: function(event) { console.log('the grid is now ready'); },

isScrollLag: function() { return false; }


Once the JavaScript data grid is initialized like this:

new Grid(this._nativeElement, this.gridOptions, ...);

ag-Grid attaches the object with API methods to the gridOptions that can be used to control the JavaScript data grid:

// get the grid to refresh
However, when ag-Grid is used as a React component, we don’t instantiate the datagrid directly. That’s the job of the wrapper component.
All interactions with the instance of ag-Grid occurs through the component instance. For example, we don’t have direct access to the API object attached by the grid. We will access it through the component’s instance.
What should a wrapper component do?

We never pass configuration options and callbacks directly to the grid.

A React wrapper component takes the options and callbacks through React Props.

All grid options that are available for vanilla JavaScript grid should be available in React datagrid as well. We also don’t directly listen for events on the instance of ag-Grid. If we’re using ag-Grid as a React component, all events emitted by ag-Grid should be available through React components props.

This all means that a React specific datagrid wrapper around ag-Grid should:

  • implement a mapping between input bindings (like rowData) and ag-Grid’s configuration options.
  • should listen for events emitted by ag-Grid and define them as component outputs
  • listen for changes in component’s input bindings and update configuration options in the grid
  • expose API attached by ag-Grid to the gridOptions through its properties

The following example demonstrates how React datagrid is configured in a template using React Props:


// useful for accessing the component directly via ref

// these are simple attributes, not bound to any state or prop

// these are bound props, so can use anything in React state or props

// this is a callback

// these are registering event callbacks
onGridReady={this.onGridReady.bind(this)}" // inside onGridReady, you receive the grid APIs if you want them


Now that we understand the requirement, let’s see how we implemented it at ag-Grid.

React Wrapper Implementation

First, we need to define a React component AgGridReact that represents our React data grid in templates. This component will render a DIV element that will serve as a container for the datagrid. To get a hold of the native DIV element we use the Refs functionality:

export class AgGridReact extends React.Component {
protected eGridDiv: HTMLElement;

render() {
    return React.createElement("div", {
        style: ...,
        ref: e =&gt; {
            this.eGridDiv = e;
    }, ...);


Before we can instantiate ag-Grid, we also need to collect all options. All ag-Grid properties and events come as React Props on the AgGridReact component. The gridOptions property is used to store all datagrid options. We need to copy all configuration options from React props as soon as they become available.

To do that, we’ve implemented the copyAttributesToGridOptions function. It’s just a utility function that copies properties from one object to the other. Here’s the gist of the function:

export class ComponentUtil {
public static copyAttributesToGridOptions(gridOptions, component, ...) {
// copy all grid properties to gridOptions object
.forEach(key => {
if (typeof component[key] !== 'undefined') {
gridOptions[key] = component[key];


     return gridOptions;


The options are copied in the componentDidMount lifecycle method after all props have been updated. This is also the hook where we instantiate the grid. We need to pass a native DOM element to the data grid when it’s being instantiated, so we’ll use the DIV element captured using refs functionality. Here’s how it all looks:

export class AgGridReact extends React.Component {
gridOptions: AgGrid.GridOptions;

componentDidMount() {

    let gridOptions = this.props.gridOptions || {};
    if (AgGridColumn.hasChildColumns(this.props)) {
        gridOptions.columnDefs = AgGridColumn.mapChildColumnDefs(this.props);

    this.gridOptions = AgGrid.ComponentUtil.copyAttributesToGridOptions(gridOptions, this.props);

    new AgGrid.Grid(this.eGridDiv, this.gridOptions, gridParams);

    this.api = this.gridOptions.api;
    this.columnApi = this.gridOptions.columnApi;


You can see above that we also check if there are children that are passed as columns and add then to configuration options as column definitions:

if (AgGridColumn.hasChildColumns(this.props)) {
gridOptions.columnDefs = AgGridColumn.mapChildColumnDefs(this.props);
Synchronizing grid properties updates

Once the grid is initialized, we need to track changes to React Props to update configuration options of the datagrid. ag-Grid implements API to do that, for example, if the headerHeight property changes there’s the setHeaderHeight method to update the height of a header.

React uses componentWillReceiveProps lifecycle method to notify a component about changes. This is where we put our update logic:

export class AgGridReact extends React.Component {
componentWillReceiveProps(nextProps: any) {
const changes = <any>{};
const changedKeys = Object.keys(nextProps);

    changedKeys.forEach((propKey) =&gt; {
        if (!this.areEquivalent(this.props[propKey], nextProps[propKey])) {
            changes[propKey] = {
                previousValue: this.props[propKey],
                currentValue: nextProps[propKey]
    AgGrid.ComponentUtil.getEventCallbacks().forEach((funcName: string) =&gt; {
        if (this.props[funcName] !== nextProps[funcName]) {
            changes[funcName] = {
                previousValue: this.props[funcName],
                currentValue: nextProps[funcName]

    AgGrid.ComponentUtil.processOnChange(changes, this.gridOptions, this.api, this.columnApi);


Basically we go over the list of ag-Grid’s configuration properties and callbacks and check if any of them have changed. We put all changes in the changes array and then process them using processOnChange method.

The method does two things. First, it goes over the changes in React Props and updates properties on the gridOptions object. Next, it calls API methods to notify the grid about the changes:

export class ComponentUtil {
public static processOnChange(changes, gridOptions, api, ...) {
// reflect the changes in the gridOptions object
.forEach(key => {
if (changes[key]) {
gridOptions[key] = changes[key].currentValue;


    // notify Grid about the changes in header height
    if (changes.headerHeight) {

    // notify Grid about the changes in page size
    if (changes.paginationPageSize) {



Exposing API

Interacting with the React grid at run time is done through the grid API. You may want to adjust the columns size, set new data source, get a list of all selected rows etc. When the JavaScript datagrid is initiated, it attaches the api object to the grid options object. To expose this object, we simply assign it to the component instance:

export class AgGridReact extends React.Component {
componentDidMount() {
new AgGrid.Grid(this.eGridDiv, this.gridOptions, gridParams);

    this.api = this.gridOptions.api;
    this.columnApi = this.gridOptions.columnApi;


And that’s it.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

React Native - The Practical Guide

MERN Stack Front To Back: Full Stack React, Redux & Node.js

Build a Basic CRUD App with Node and React

Setting A React Project From Scratch Using Babel And Webpack

JavaScript Basics Before You Learn React

Build a React Calendar Component from scratch

Learn ReactJS with Webpack 4, Babel 7, and Material Design

Using Typescript with modern React (i.e. hooks, context, suspense)

This article was originally published on https://scotch.io

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.


Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types


An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).


An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:



A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:


In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
else (condition) {
statement b;

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
else {
console.log("Wrong, please try again");

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
case 2:
code block 2
code block 3

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
case "football":
console.log("I love football!");
case "cricket":
console.log("I'm a huge cricket fan!");
console.log("I like other games");

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!