Getting Started with React.js and D3.js

Getting Started with React.js and D3.js

Data Driven Documents (D3.js) is a JavaScript library used to create visualizations of data using HTML, CSS, and SVG. It does this by binding data to the DOM (Document Object Model) and its elements and allowing them to transform when the data changes.

Data Driven Documents (D3.js) is a JavaScript library used to create visualizations of data using HTML, CSS, and SVG. It does this by binding data to the DOM (Document Object Model) and its elements and allowing them to transform when the data changes.

For example, let’s say we want to create a pie chart of amounts of books in every genre in a library. We have some data which we update every time a librarian enters a new book. We store it in the application state, in a variable called “books”.

const [books, setBooks] = useState(initialBooks)
const initialBooks = [
    {
        name: "Harry Potter and the Philosophers Stone",
        author: "J. K. Rowling",
        genre: "fantasy"
    },{
        name: "The Pedagogy of Freedom",
        author: "Bell hooks",
        genre: "non-fiction"
    },{
        name: "Harry Potter and the Chamber of Secrets",
        author: "J. K. Rowling",
        genre: "fantasy"
    },{
        name: "Gilgamesh",
        author: "Derrek Hines",
        genre: "poetry"
    }
]

Right now we could create a chart that has 50% of fantasy, 25% of non-fiction and 25% of poetry. When the librarian adds a new book to the database, the data changes, and your graft shifts. Let’s say we add “50 vegan dishes”.

setBooks(books.concat(
    {
        name: "50 vegan dishes",
        author: "Antti Leppänen",
        genre: "non-fiction"
    }
))

When this data changes, our D3 graph updates the DOM to match the new data. We now have 40% fantasy, 40% non-fiction, and 20% poetry. D3 makes manipulating the website DOM easy. This means that you can use it to create, update and delete elements in the page structure.

If you want to follow along with this example, you can use Create React App to create a simple React web app. If React is still unfamiliar to you, you can check out this tutorial from the React documentation.

  1. Create a new app, called my-d4-app npx create-react-app my-d3-app. Change directory into the created folder by using cd my-d3-app.
  2. Install D3 by running npm install d3 --save .
  3. Import D3 to App.js by adding import * as d3 from d3 . You need to use import * (“import everything”) since D3 has no default exported module.

Selecting DOM elements

D3 makes manipulating the DOM easy. For example, let’s try to change all <p></p> -elements to have an inline style setting the color to blue.

d3.selectAll("p").style("color", "blue")

The .selectAll()-method allows us to select all elements of a specific type. We can also use .select() to select individual nodes.

The React library also manipulates the DOM. This means we have to make a little extra effort to get it to work together with D3. Luckily React already has a solution for allowing targeting and updating DOM elements. To do this, React uses references.

Let’s create a <div>-element and add a reference to it, and then use the reference to pick it up with D3.

d3.select(this.refs.myDiv).style(“background-color”, “blue”)
render(<div ref=”myDiv”></div>)

Appending elements to the DOM

Once you have selected the element you want to manipulate, you can start appending more elements to it. For example, imagine we have a <ol ref="myList">. We can use D3 to append a new list item element, containing the text “bananas”.

d3.select(this.refs.myList)
    .append("li")
    .text("bananas")

Using data to create

You can make D3 aware of your data by selecting DOM elements and attaching the data to them using .data(). D3 has a method called .enter(), which is often used for working with data. It signifies that these data elements need to be added to the DOM. Enters counterpart, .exit() , is used to signify those elements that no longer exist in the data but do exist in the DOM. We can use it to remove those elements together with remove, as in .exit().remove().

Let’s take a look at an example.

import React, { component } from 'react'
import * as d3 from 'd3'
class App extends Component {
    const temperatureData = [ 8, 5, 13, 9, 12 ]
    d3.select(this.refs.temperatures)
        .selectAll("h2")
        .data(temperatureData)
        .enter()
            .append("h2")
            .text("New Temperature")
 
    render(<div ref="temperatures"></div>)
}
export default App

This reads “D3, select the element with reference ‘temperatures’. Then, attach temperatureData to it’s <h2>-elements. For the parts of data which aren’t represented in the DOM yet, append a new <h2>-element with the text “New Temperature”.

Wait, now it says “New temperature” over and over again! What if we want to display the actual datapoint value?

Properties as functions

In D3, styles, attributes and other element properties can be set using functions. Let’s refactor the code above to use a function that sets the texts of the <h2>-elements to the datapoint value they represent.

d3.select(this.refs.temperatures)
    .selectAll("h2")
    .data(temperatureData)
    .enter()
        .append("h2")
        .text((datapoint) => datapoint + " degrees")

We can use an arrow function to take the datapoint value and return the value added to “ degrees”. Functions in properties allow us to get creative with the elements. In this example from the D3 documentation, a paragraph is given a random color using a function to set the elements style property.

d3.selectAll("p")
    .style("color", function() {
        return "hsl(" + Math.random() * 360 + ",100%,50%)";
    }
);

You can also use conditionals, just as in any function. Let’s say we want to set the style of an element of our temperature list based on the data.

d3.select(this.refs.temperatures)
    .selectAll("h2")
    .data(temperatureData)
    .enter()
        .append("h2")
        .text((datapoint) => `${datapoint} degrees`)
        .style((datapoint) => {
            if (datapoint > 10) {
                return "red"
            } else { return "blue" }     
        }) 

However, adding inline styles is a tedious job, and we would like to use classes and ids instead so that we could set the styles in our CSS. To set attributes like classes and ids, we use .attr(). The code above could be refactored to .attr("class", (datapoint) => { datapoint > 10 ? "highTemperature" : "lowTemperature" }.

Animating with transitions

Finally, D3 makes animating transitions easy. We could change text color to red.

d3.select(this.ref.descr)
    .transition()
    .style("background-color", "red");
render(<p ref="descr"></p>)

We can modify the animation to happen after 1 second using .duration(1000). We can also use functions together with transitions. For example, we can make our elements to appear in a staggered transition. The following example from the D3 documentation makes circles appear one at a time, using a delay() function that takes dataPoint and iteration as parameters, and returns the iteration multiplied by 10. Iteration refers to the position of the datapoint in the list of data.

d3.selectAll("circle").transition()
    .duration(750)
    .delay(function(dataPoint, iteration) => iteration * 10)
    .attr("r", (dataPoint) => Math.sqrt(d * scale))

Our first chart

Let’s create a new component. Create a new file, called BarChart.js. Modify App.js to look like this.

import React from React
import BarChart from './BarChart'
const App = () => {
    return ( <BarChart /> )
}

Paste the following boilerplate into BarChart.js. Call npm start to start the app.

import React, { Component } from 'react'
import * as d3 from 'd3'
class BarChart extends Component {
    componentDidMount() {
        const data = [ 2, 4, 2, 6, 8 ]
        this.drawBarChart(data)
    }
    drawBarChart(data)  {}
    render() { return <div ref="canvas"></div> }
}
export default BarChart

We have a set of dummy data, which we pass to the drawing function as a parameter. From now on, we’ll be working inside drawBarChart(). First, select the div with the reference canvas. Inside drawBarChart(), we append a svg element inside the div we referenced. We set the svg to have a with of 600, a height of 400 and a black border. You should see this empty box appear on the page.

const svgCanvas = d3.select(this.refs.canvas)
    .append(“svg”)
    .attr(“width”, 600)
    .attr(“height”, 400)
    .style(“border”, “1px solid black”)

An empty SVG element with a black border.

Next, we need some bars on our bar chart. We select all rect elements, or rectangles, of the svg. Then we append the data to the rectangles and use enter to step into the data. For each data in the element, we append a rectangle with a width of 40 and the height of the datapoint value multiplied by 20.

svgCanvas.selectAll(“rect”)
    .data(data).enter()
         .append(“rect”)
         .attr(“width”, 40)
         .attr(“height”, (datapoint) => datapoint * 20)
         .attr(“fill”, “orange”)

After appending the rectangles with data to the SVG.

Wait, why does it look like we only have one rectangle? Since we didn’t specify where on the svg the rectangle should appear, they all piled up at 0, 0. Let’s add the x and y positions to them. Let’s also refactor the code to keep the canvas width, height and the scale of the bars in variables.

drawBarChart(data) {
const canvasHeight = 400
const canvasWidth = 600
const scale = 20
const svgCanvas = d3.select(this.refs.canvas)
    .append(“svg”)
    .attr(“width”, canvasWidth)
    .attr(“height”, canvasHeight)
    .style(“border”, “1px solid black”)
svgCanvas.selectAll(“rect”)
    .data(data).enter()
        .append(“rect”)
        .attr(“width”, 40)
        .attr(“height”, (datapoint) => datapoint * scale)
        .attr(“fill”, “orange”)
        .attr(“x”, (datapoint, iteration) => iteration * 45)
        .attr(“y”, (datapoint) => canvasHeight — datapoint * scale)
}

Now we set the position x to the iteration multiplied by 45, which is 5 wider than the column width, leaving a small gap between the columns. The y position is a bit trickier. We set it to the canvas height minus the height of the bar, which is the datapoint value multiplied by 20. Now our chart looks like this.

After setting the x and y positions of the rectangles.

To give our bars a final touch, let’s add the data point values to the bars. We append some text elements to the svg and set their x-attribute 10 units greater than each bars starting point. We set the y-attribute to be 10 units less than the starting point of the bar.

svgCanvas.selectAll(“text”)
    .data(data).enter()
        .append(“text”)
        .attr(“x”, (dataPoint, i) => i * 45 + 10)
        .attr(“y”, (dataPoint, i) => canvasHeight - dataPoint * scale - 10)
        .text(dataPoint => dataPoint)

Adding text labels to our bars.

Now the texts sit just above the bars. You can continue working with the chart, adding styles (using .attr("class", "bar") and adding a CSS file. You can also add an axis to the chart and add a tooltip when mousing over the bar.

Get creative and enjoy!

Working with D3 can seem difficult in the beginning. Once you get the basics down it becomes a powerful tool to express and visualize data. I recommend using D3 over picking a ready-made chart library, since it allows for more personal and modifiable pieces.

Finally, learning D3 is also a good way of getting fluent at traversing and manipulating the DOM. Understanding the DOM is often a quality interviewers look for in front end developers.

Resources:

D3 Tutorials suggested by D3

React tutorial from the React documentation

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;
age=22;

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

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

Objects

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).

Arrays

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=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

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:

shopping[0];		

Functions

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:

product(8,2);

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) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

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] {
console.log("Correct!");
}
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);
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);
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
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

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!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

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!