sadhucoder
sadhucoder

Reputation: 320

How do I extend React components already in use?

This applies to just about any scenario along these lines:

I have a React app that uses React Router <Link>s, and they are scattered throughout my app. I want to extend or prototype the <Link> component so that there is a new attribute when they are rendered. (I just want to add an attribute to all Link tags.)

How can I update the Link component that is being used throughout the app, to have a new attribute [without creating a new component, like <CustomAttributeLink>]?

Thanks

Upvotes: 0

Views: 434

Answers (2)

Jorge Baralt
Jorge Baralt

Reputation: 76

The best way to do this is by cloning the element, you should use React.cloneElement. To make the component usable everywhere, just create a new component using it, and export it.

import React from "react";
import {Link} from "react-router";

const CustomLinkAttribute = React.cloneElement(Link, {
  newProp: "New prop val here"
});
export default CustomLinkAttribute;

Upvotes: 2

Ali Mousavi
Ali Mousavi

Reputation: 915

You can clone the element and add the extra props using React.cloneElement e.g:

var clonedElementWithExtraProps = React.cloneElement(
    MainElement, 
    { newProp: "This is a new prop" }
);

Return clonedElementWithExtraProps;

Upvotes: 1

Related Questions