Reputation: 151
In our project we are using React and Web Components to develop reusable UI components (which in turn will be used by various dev teams internally). Components are developed in React and registered as custom HTML elements through Web Components. We need a way through which we can define the props in HTML custom tag and access all the props in our React Component.
The HTML would be like
<custom-element props1='pageInfo' props2='mediaInfo'></custom-element>
pageInfo
and mediaInfo
will be JS Objects which will be declared in global window scope or they can be inside some other NameSpace/Object, in that case the HTML would be something like
<custom-element props1='NS.pageInfo' props2='NS.mediaInfo'></custom-element>
OR
<custom-element props1='NS.Page.pageInfo' props2='NS.Media.mediaInfo'></custom-element>
So, we need a way to get all the props defined in the HTML and resolve them as Objects and pass it on to ReactDOM.render
Currently the code to render and register custom element is,
class RegComponent extends HTMLElement {
constructor() {
super();
}
createdCallback() {
ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
}
}
document.registerElement('custom-element', RegComponent);
We want to get rid of eval and all the declared props should be fetched from HTML and passed on to ReactDOM.render
. Looking for something like,
ReactDOM.render(<App {getAllProps()}/>, this);
where getAllProps()
should return all the props name & their value. Remember that I'm using ES6. Any help would be appreciated!
Upvotes: 3
Views: 1274
Reputation: 12447
What about instead of using JSX:
ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
Use React directly, with an adapter transforming attributes into props:
ReactDOM.render(React.createElement(App, {...getAllProps(this.attributes)}), this);
function getAllProps(attributes) {
var props = {};
for (var i = 0; i < attributes.length; i++) {
props[attributes[i].nodeName] = attributes[i].nodeValue;
}
return props;
}
Upvotes: 2
Reputation: 2469
If getAllProps()
returns an object, and each property in the object is the prop you wanted, you should only need to update you render to use the spread operator(...
). This will deconstruct your object so that each property is passed to the App
as a prop
.
Here is what it would look like:
ReactDOM.render(<App {...getAllProps()}/>, this);
Upvotes: 0