Author avatar

Vivek Kumar

Cloning a React Component

Vivek Kumar

  • Jul 26, 2019
  • 7 Min read
  • 26 Views
  • Jul 26, 2019
  • 7 Min read
  • 26 Views
Web Development
React

Introduction

In the world of animation, the React components have a lot to offer. The description of the React components would be incomplete without highlighting the roles that props play in them. The props, in React, are quite resilient and upkeep the sovereignty of the child components from the parent component. In the majority of the situations demonstrated by the React Component, it is the child component that merely puts into use the props passed on by parent component. Nevertheless, there are cases where you will want to spread out the incoming props, with the help of some relatively new data, prior to the rendering of the child component.

In React, one can find an add-on that can enable the cloning of a component as well as ranging its props, simultaneously. This add-on is generally termed cloneWithProps.

Although the add-on works in general sense, if it is not working properly, as per your requirements, then you do not need to be disappointed at all. In case the add-on is not fully functional with React, React can implement a top-notch application programming interface (API). If there is a problem with the refs of component (like if it were unable to avail access to a recently cloned child components), then the API method React.cloneElement can help us with the cloning as well as extending the component. The best part is that the Application Programming Interface used here is quite genuine and easy to execute.

Cloning a React Component with React Rather Than jQuery

Here, we will try to learn not only the cloning of a React component but also how to append it somewhere else. The requirement here is to work on some of the fieldsets with the application of React.JS + Backbone.JS. In order to make it work, there has to be a table containing several rows and columns. The work here is to ensure that the first column is fixed at whatever time the total number of columns is larger than to the number of columns be showcased on the screen. It can be properly understood by the following example.

Let’s say that the total numbers of columns existing within the table are eight, but only six columns can be displayed on the big screen. Hence, the remaining two columns can be observed by scrolling in the horizontal direction.

In the current logic, it is advisable to apply jQuery in order to clone each of the first columns with respect to each row. It is going to help in the creation of a new table. This new table can be appended after the original table. In order to place it over the original table, one can use CSS; hence, it would be easier to see the successfully fixed first column.

The approach mentioned above can still witness improvement in the due course of time and it must be executed with the help of the great Document Object Model (DOM) of the CSS React.JS.

You can even start with a plain React table component, as mentioned below:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Table = React.createClass({
    render: function() {
        return <table >
            {this.props.data.map(function(row){
                return <tr >
                    {row.map(function(cell){
                        return <td > {cell} </ td>
                    })}
                </ tr>
            })}
        </ table>;
    }
});
javascript

The components mentioned above are merely a demonstration; the actual table would be far more composite and complex.

Now, the following is going to be the table that we wish to have in this component.

1
2
3
4
5
6
7
8
9
10
11
12
var DubbledTable = React.createClass({
    render: function() {
        var firstColumn = 
            this.props.data.map(function(row){
                return [row[0]]
            })
        return <span >
            <Table data = {firstColumn} />
            <Table data = {this.props.data} />
        </ span>
    }
})
javascript

Cloning the React Elements with React.cloneElement Rather Than cloneWithProps

In some of the exceptional situations, you may wish to generate a clone of a React component with the aid of various props that were associated with the original component. For instance, cloning React components by accessing the this.props.children and then rendering them via various props.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var cloneWithProps = require('react-addons-clone-with-props');

var _makeBlue = function(element) {
  return cloneWithProps(element, {style: {color: 'blue'}});
};

var Blue = React.createClass({
  render: function() {
    var blueChildren = React.Children.map(this.props.children, _makeBlue);
    return <div > {blueChildren} </ div>;
  }
});

ReactDOM.render(
  <Blue>
    <p > This text is blue. </ p>
  </ Blue>,
  document.getElementById('container')
);
javascript

Here, cloneWithProps is not going to transfer the key or ref into the cloned component. The styleprops, as well as className, are automatically merged.

Note: cloneWithProps usually does not relocate the key prop to a cloned element. If you have an objective to safeguard the key, then the best thing you can do is to include it to the extraProps object.

The command associated with the above measure is shown below:

1
 var clonedComponent = cloneWithProps(originalComponent, { key : originalComponent.props.key });
javascript

In select situations, an element may want to modify the props of another element which it doesn’t own one way or an other. Likewise, modifying the className of an element passed in the form of this.props.children. In other conditions, it may want to make a number of copies of an element passed through it; this is made feasible with cloneWithProps().

1
ReactComponent React.addons.cloneWithProps(ReactComponent component, object? extraProps)
javascript

The common question that arises here is, “Why not create a shallow copy of an element and merge any props delivered by extraProps?” The props are combined in an identical manner as transferPropsTo(); hence, the props, such as className, are going to be combined in a wise manner.

Conclusion

In this guide, you have learned about several aspects related to the cloning of a React component. From the reasons behind cloning a React Component with React.js rather than jQuery.js, to the cloning of elements with cloneWithProps, as well as the special cases where the application of React.cloneElement can play a pivotal role.

References

While writing this guide, the following resources have been referenced:

0