ReactJS Interview Questions

ReactJs Interview Questions

ReactJs Interview Questions

1. What is Virtual DOM? List down the steps on how does React Handle change to the DOM?

A virtual DOM object is a representation of a DOM object, like a lightweight copy. When you render a JSX element, every single virtual DOM object gets updated. Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update. Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM.
In summary, here’s what happens when you try to update the DOM in React:

  • The entire virtual DOM gets updated.
  • The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
  • The changed objects, and the changed objects only, get updated on the real DOM.
  • Changes on the real DOM cause the screen to change.

2. Why can’t we call this.setState from render function of React Component?

this.setState updates the state of the component and since the component state is updated, it calls render method on its own. So, if we call this.setState from render method there will be infinite loop.

3. What do you mean by Automatic Binding of context in React?

Automatic binding allows you to pass functions as props, and any this values in the functions’ bodies will automatically refer to whatever they referred to when the function was defined. Consider following code example:

 class Parent extends React.Component {
    inputChanged() {
        //do something using context this
    },
    render() {
        return <Child onChange={this.inputChanged}> 
 } 
 };
class Child extends React.Component({
    render() {
        return <input onChange={this.props.onChange}> 
 } 
};

When input changes in Child component, inputChanged function of Parent component is called.
Considering dynamic context binding in Javascript, inputChanged must have this referring to Child component,
but because of automatic binding by ReactJS, the context refers to where the function is defined hence this
in inputChanged refers to Parent component.

4. What is Stateless Functional Component and how do we define them?

Component written directly as function is called stateless functional component. e.g.

function Card(props) {
    return (
        
{props.name} {props.email} {props.phone}
) }

When a component class has nothing else but only render function and returns JSX then stateless functional component can be used. The props parameter passed to the function is equivalent to {this.props}.

5. What are propTypes and how do we define propTypes for Stateless Functional Component?

If a component class expects the prop to be passed from parent component then propTypes is to be used. It helps in mainly in two purposes:

  • Validation w.r.t. datatype, required etc
  • Documenting the expected properties.

propTypes in components:

var Child = React.createClass({
    propTypes: {
        name: React.PropTypes.string
    },
    render: function() {
        return {this.props.name}
    }
})

propTypes in stateless functional component should be provided as direct function properties:

function Child(props){
    return {this.props.name}
} Child.propTypes = { name: React.PropTypes.string };

Contd…

Credits: http://codecademy.com/

Advertisements

Multi Level Pie Chart Using D3

multilevelPieChart

Using D3, the MultiLevel pie chart is constructed from a hierarchical data (shown below). This could be achieved by modifying the original example of pie chart in mike’s blog.

The implementation is a 2 step process. In the first step the hierarchical data is stored for each level and in the second step the corresponding pie charts are drawn (by tweaking inner and outer radius) for each level, using the stored data.

To store the data for each level, I have used BFS (Breadth First Search) to traverse the array of objects and then storing the each level’s data in an array, where the index of the array being the level of the in the nested object structure. I modified a little, the solution proposed in this blog to achieve the same.

var setMultiLevelData = function(data) {
    if (data == null)
        return;
    var level = data.length,
        counter = 0,
        index = 0,
        currentLevelData = [],
        queue = [];
    for (var i = 0; i < data.length; i++) {
        queue.push(data[i]);
    };
    while (!queue.length == 0) {
        var node = queue.shift();
        currentLevelData.push(node);
        level--;
        if (node.subData) {
            for (var i = 0; i < node.subData.length; i++) {
                queue.push(node.subData[i]);
                counter++;
            };
        }
        if (level == 0) {
            level = counter;
            counter = 0;            multiLevelData.push(currentLevelData);
            currentLevelData = [];
        }
    }
}

 

Once the data for each level is obtained, the all that remains is drawing multiple pie chart circles iteratively (for each level), one outside the other. I am using the function “drawPieChart” shown in below code (also explained in Mike’s blog) for each level by iterating over the stored multiLevel Data.

 

var drawPieChart = function(_data, index) {
    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
            return d.nodeData.population;
        });
    var arc = d3.svg.arc()
        .outerRadius((index + 1) * pieWidth - 1)
        .innerRadius(index * pieWidth);

    var g = svg.selectAll(".arc" + index).data(pie(_data)).enter().append("g")
        .attr("class", "arc" + index);

    g.append("path").attr("d", arc)
        .style("fill", function(d) {
            return color(d.data.nodeData.age);
        });

    g.append("text").attr("transform", function(d) {
            return "translate(" + arc.centroid(d) + ")";
        })
        .attr("dy", ".35em").style("text-anchor", "middle")
        .text(function(d) {
            return d.data.nodeData.age;
        });
}
//Calling drawPieChart for each level's data
for (var i = 0; i < multiLevelData.length; i++) {
    var _cData = multiLevelData[i];
    drawPieChart(_cData, i);
}

One point to notice in above code is, to have inner radius of the outer pie chart as outer radius of it’s immediate inner pie chart and so on, we used:

var arc = d3.svg.arc()
        .outerRadius((index + 1) * pieWidth - 1)
        .innerRadius(index * pieWidth);
//index is the index of corresponding level in the nested data object. The structure of the data object is shown at the bottom.

Refer following codepen snippet for complete working code:

The hierarchical data looks like:

{
    "nodeData": {
        "age": "5",
        "population": 60
    },
    "subData": [{
        "nodeData": {
            "age": "5",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "5",
                "population": 60
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "5-35",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "5-15",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "5-10",
                "population": 30
            }
        }, {
            "nodeData": {
                "age": "10-15",
                "population": 30
            }
        }]
    }, {
        "nodeData": {
            "age": "15-35",
            "population": 40
        },
        "subData": [{
            "nodeData": {
                "age": "15-25",
                "population": 25
            }
        }, {
            "nodeData": {
                "age": "25-35",
                "population": 15
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "35-65",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "35-50",
            "population": 75
        },
        "subData": [{
            "nodeData": {
                "age": "35-50",
                "population": 75
            }
        }]
    }, {
        "nodeData": {
            "age": "50-65",
            "population": 25
        },
        "subData": [{
            "nodeData": {
                "age": "50-65",
                "population": 25
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "65",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "65-75",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "65-75",
                "population": 60
            }
        }]
    }, {
        "nodeData": {
            "age": "75",
            "population": 40
        },
        "subData": [{
            "nodeData": {
                "age": "75",
                "population": 40
            }
        }]
    }]
}