Reputation: 320
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
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
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