Clone and extend JSX elements in React

In this article, we will learn how to clone and extend JSX elements in React.

Clone and extend jsx element in React

Often times we face situation during the development to clone or extend the JSX element (children) and add additional props to them.

While JSX (JavaScript XML) are JavaScript objects that can be written like HTML or XML tags, we cannot extend them like how we extend the regular objects in JavaScript like using the spread operators.

Because the JSX are converted to the React.Element using the Babel transipilier that represent composite tree (nested objects).

To clone and extend any JSX elements, we have to clone them using React.cloneElement.

React.cloneElement(element, props, children);

React.cloneElement is a function that clones the given JSX elements along with it we can pass extra parameters such as list of properties and children.

export default function App() {
  return <div className="App">{clonedElement}</div>;
}

const Element = ({ title, goodProgrammingSite, children }) => <div>{children} to {title} it is a good programming site: {goodProgrammingSite ? 'true': 'false'}</div>;

const clonedElement = cloneElement(
  <Element title="Learnersbucket">Hello</Element>,
  { goodProgrammingSite: true },
  "Welcome"
);

console.log(clonedElement); 
// <Element title="Learnersbucket" goodProgrammingSite={true}>Welcome</Element>

This is really helpful when you want to pass few extra props to the children and extend their functionality.

For example, in this stepper component, we want the child components to have the onNext and onPrev navigation option so that they can move to the next or the pervious steps. Thus we clone the children and pass these props to them.