The cloneElement API from React allows us to extend and modify the functionality of components that we render. We'll start by creating a simple component that just renders some punctuation and some text, so say const add punctuation is equal to a function, so this will be a stateless React component.
Say text, punctuation, and then just get the rest of the props, and then we will return a span with our prop spread. This will be anything that if you added a class name or a style, etc., it would be put onto the span. We'll then render our text and our punctuation.
If we use this component, apply some text and say, "Hello, world," and a punctuation, give it an exclamation point, close this, and we go to our browser, we can see that, "Hello, world," with our punctuation is being rendered.
Now we'll create an emphasize component, say const emphasize is equal to times, which will be the number of times we'll duplicate the punctuation, as well as the children. Here we'll take return React.cloneElement.
The cloneElement has an API that takes the child, and then the additional props that you would like to add. In our case, we would say children, because we're only going to be referencing a single child, and then we can say punctuation is equal to the child props.punctuation.repeat the number of times that we want.
This is currently overriding the original punctuation that we put in here. Now, if we just wrap our component, we say emphasize, we'll say times 10 and close this around it so that this add punctuation is a child of emphasize. Now if we switched our browser, see when we refresh that it's emphasized our punctuation 10 times.
You could do more than just override properties. You can also add additional properties that were not originally declared on the component. For example, you can say style, and we'll pass in font weight, bold.
This is a property that was not originally declared here. However, because our add punctuation takes the rest of our props and puts them on the span, this will be inside of here and put onto the span.
Now if we save this and we go back to our browser, when it refreshes, you can see that we are adding the property font weight bold, and we are still also overriding our punctuations and emphasizing it 10 times.