React Regex string to html - javascript

I am currently working on a project and running into a little issue with parsing messages for links. I was wondering if there a better way to handle the conversion of a string of html to html then using dangerouslySetInnerHTML. As the method says it could be dangerous and I rather look for a cleaner way to handle it.
//Function for regex
var www_reg = /(?:^|[^"'])(^|[^\/])(www\.[\S]+(\b|$))/gim;
message = message.replace(www_reg, '$1$2');
return {__html: message};
//Render
<div className='message-class' onClick={this.clickedLink} dangerouslySetInnerHTML={this.replaceURLWithHTMLLinks(display_message.last_message)}>

Something simple would be to split the string by the regex and turn the urls into JSX elements. Elegant solution that doesn't require dangerouslySetInnerHTML.
class Example extends React.Component {
constructor() {
super();
this.state = {
string: 'Hello www.example.com World www.stackoverflow.com',
message: [],
};
}
componentDidMount() {
let www_reg = /(www\.[\S]+(\b|$))/gim;
let blocks = this.state.string.split(www_reg);
let message = blocks.map(block => {
if (block.match(www_reg)) {
return <a href={'//' + block}>{block}</a>;
} else {
return block;
}
});
this.setState({ message });
}
render() {
return(
<div>{this.state.message}</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='View'></div>
PS: I had some trouble using your regex (it cut off some characters), so I modified it a bit. But it should work anyways, since I'm only using native JS functions here.

You could parse the message string into an array of text and URLs (keeping order) and then map over that turning the URLs into actual React link elements. You could then plop that array straight into your div <div>{arrayOfParts}</div>
It looks like there is an npm module react-linkify that will do that for you, or you can look at the source code here if you want to re-implement yourself.

Related

Can you use a backdraftjs watchable to make a component completely re-render?

This is a contrived example but it is similar to real-life situations where, for example, you might have a list of links built from data that you are AJAXing in from a server.
import {Component, e, render} from './node_modules/bd-core/lib.js';
// a list of strings that for alert when you click them
class AlertLinkList extends Component.withWatchables('data') {
handleClick(event){
alert(event.target.innerHTML);
}
bdElements() {
return e.div(
{
// bdReflect: ?????
},
['yes', 'no', 'maybe'].map(
txt => e.div({bdAdvise: {click: 'handleClick'}}, txt)
)
)
}
}
var linkList = render(AlertLinkList, {}, document.body);
// I would like to change the strings but this (obviously) does nothing
linkList.data = ['soup', 'nuts', 'fish', 'dessert'];
I can't think of a straightforward way to solve this.
bdReflect only works on writable DOM attributes, I think, so for example I could use it to replace the innerHTML of the component but then I think I lose the bdAdvise assignments on the links (and it also seems kinda kludgey).
Any ideas?
OK here's one pattern that works for this...
get rid of the watchables in AlertLinkList
instead, use kwargs to populate the list
wrap the list in another component that simply re-renders the list with new content whenever the content changes (e.g. after fetching new content from the server)
// a list of strings that alert when you click them
class AlertLinkList extends Component {
handleClick(event){
alert(event.target.innerHTML);
}
bdElements() {
return e.div(
this.kwargs.items.map(
txt => e.div({bdAdvise: {click: 'handleClick'}}, txt)
)
)
}
}
// a wrapper that provides/retrieves data for AlertLinkList
class LinkListWrapper extends Component {
bdElements() {
return e.div(
{},
e.a(
{bdAdvise: {click: 'updateList'}},
'Click to Update List',
),
e.div({bdAttach: 'listGoesHere'}),
);
}
updateList(event) {
// the data below would have been retrieved from the server...
const resultRetrievedFromServer = ['soup', 'nuts', 'fish', 'dessert'];
this.renderList(resultRetrievedFromServer)
}
renderList(items) {
render(AlertLinkList, {items}, this.listGoesHere, 'only')
}
postRender() {
const initialData = ['yes', 'no', 'maybe']
this.renderList(initialData);
}
}
var linkList = render(LinkListWrapper, {}, document.body);
The only issue I see here is that it may be suboptimal to re-render the entire wrapped component if only one small part of the data changed, though I suppose you could design around that.
Let's begin solving this problem by describing the public interface of AlertLinkList:
A component that contains a homogeneous list of children.
The state of each child is initialized by a pair of [text, url].
The list is mutated en masse.
Given this, your start is almost perfect. Here it is a again with a few minor modifications:
class AlertLinkList extends Component.withWatchables('data') {
handleClick(event) {
// do something when one of the children is clicked
}
bdElements() {
return e.div({}, this.data && this.data.map(item => e(AlertLink, { data: item })));
}
onMutateData(newValue) {
if (this.rendered) {
this.delChildren();
newValue && newValue.forEach(item => this.insChild(AlertLink, { data: item }));
}
}
}
See https://backdraftjs.org/tutorial.html#bd-tutorial.watchableProperties for an explanation of onMutateData.
Next we need to define the AlertLink component type; this is trivial:
class AlertLink extends Component {
bdElements() {
return e.a({
href: this.kwargs.data[1],
bdAdvise: { click: e => this.parent.handleClick(e) }
}, this.kwargs.data[0]);
}
}
The outline above will solve your problem. I've written the pen https://codepen.io/rcgill/pen/ExWrLbg to demonstrate.
You can also solve the problem with the backdraft Collection component https://backdraftjs.org/docs.html#bd-core.classes.Collection
I've written a pen https://codepen.io/rcgill/pen/WNpmeyx to demonstrate.
Lastly, if you're interested in writing the fewest lines of code possible and want a fairly immutable design, you don't have to factor out a child type. Here's a pen to demonstrate that: https://codepen.io/rcgill/pen/bGqZGgW
Which is best!?!? Well, it depends on your aims.
The first solution is simple and general and the children can be wrangled to do whatever you want them to do.
The second solution is very terse and includes a lot of additional capabilities not demonstrated. For example, with the backdraft Collection component
mutating the collection does not destroy/create new children, but rather alters the state of existing children. This is much more efficient and useful when implementing things like large grids.
you can mutate an individual elements in the collection
The third solution is very terse and very fixed. But sometimes that is all you need.

Cant run JavaScript tagged template from within imported object

I am trying to convert a websites JavaScript into chucks compatible with webpack bundling, basically i need to export/import the needed scripts for a multi page website and then pack them into 1 file per page, it do however cause me some troubles
The script worked perfectly fine before but now it do not work as previously
I have a templater function that use string listerals and string manipulation the templater function is originally inspired by this post, it is however modified a bit
export const templater = (parts) => {
return (data) => {
let res = parts[0];
for (let i=1; i < parts.length; i++) {
const val = arguments[i];
if (typeof val == "function") {
res += val(data);
} else {
if (data) {
if(data.hasOwnProperty(val)) {
res += data[val];
}
}
}
res += parts[i];
}
return res;
}
};
I have a script that handles the string literal its an object with the key 'template' which calls the imported templater function
import {templater} from '../functions/cc-templater-function.js';
export let complianceHandler = {
template: templater`
<div class="compliance-overlay">
<div id="compliance-wrapper" class="compliance-wrapper ${'type'}">
<p class="compliance-message">${'message'}</p>
<button id="compliance-yes" data-answer="yes">Yes</button><button id="compliance-no" data-answer="no">No</button>
</div>
</div>
`
}
I have this script which passes the JavaScript object to the handler which uses it in the templater function
import {complianceHandler } from './objects/cc-compliance-handler-object.js';
export let testObject = {
remove: () => {
document.querySelector('#myelem').insertAdjacentHTML("beforeend", complianceHandler.template({
message: 'Are you sure you want to do this?'
}));
}
}
The above is a simplified/stripped version of the real code
When the testObject.remove() is called i get this error: Cannot read property 'call' of undefined
I cant see the method/function named call anywhere, i'm kinda lost at this point on how to debug and fix this
Everything bundles fine when bundling with webpack
Everything works this way in the normal code that are not bundled with webpack and exported/imported (the old code)
Does anybody know how to solve this? i have tried to modify the code in various ways, but i continue to get the same error
export let complianceHandler = {
template: templater`
<div class="compliance-overlay">
<div id="compliance-wrapper" class="compliance-wrapper ${'type'}">
<p class="compliance-message">${'message'}</p>
<button id="compliance-yes" data-answer="yes">Yes</button><button id="compliance-no" data-answer="no">No</button>
</div>
</div>
`
}
This is exporting an object with a template string property generated from calling the templater function.
Later on, you're importing this and trying to call the template property. Since it's a string, calling it doesn't make sense:
complianceHandler.template({
message: 'Are you sure you want to do this?'
})
It sounds like what you're wanting to do is to make template a function instead:
export let complianceHandler = {
template: ({ type, message }) => templater`
<div class="compliance-overlay">
<div id="compliance-wrapper" class="compliance-wrapper ${type}">
<p class="compliance-message">${message}</p>
<button id="compliance-yes" data-answer="yes">Yes</button><button id="compliance-no" data-answer="no">No</button>
</div>
</div>
`
}
Notice I also fixed the template placeholders (${type}, not ${'type'} so the variable is used, not the literal string 'type'). It should also be noted that if you want to generate valid HTML, you should be HTML-encoding your variables before inserting into the HTML unless you want the variables to be HTML instead of text.

how to pass objects in web component javascript [duplicate]

My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.
JavaScript objects can obviously be sent out in the event's detail field, but what if the element needs a lot of data passed into it. Is there a way to provide it with an object in JavaScript.
What if the element for instance contains a variable number of parts that needs to be initialized or changed dynamically (e.g. a table with a variable number of rows)? I can imagine setting and modifying an attribute consisting of a JSON string that is parsed inside the component, but it does not feel like an elegant way to proceed:
<my-element tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>
Or can you make the element listen to events from the outside that contains a payload of data?
Passing Data In
If you really want/need to pass large amounts of data into your component then you can do it four different ways:
1) Use a property. This is the simplest since you just pass in the Object by giving the value to the element like this: el.data = myObj;
2) Use an attribute. Personally I hate this way of doing it this way, but some frameworks require data to be passed in through attributes. This is similar to how you show in your question. <my-el data="[{a:1},{a:2}....]"></my-el>. Be careful to follow the rules related to escaping attribute values. If you use this method you will need to use JSON.parse on your attribute and that may fail. It can also get very ugly in the HTML to have the massive amount of data showing in a attribute.
3 Pass it in through child elements. Think of the <select> element with the <option> child elements. You can use any element type as children and they don't even need to be real elements. In your connectedCallback function your code just grabs all of the children and convert the elements, their attributes or their content into the data your component needs.
4 Use Fetch. Provide a URL for your element to go get its own data. Think of <img src="imageUrl.png"/>. If your already has the data for your component then this might seem like a poor option. But the browser provides a cool feature of embedding data that is similar to option 2, above, but is handled automatically by the browser.
Here is an example of using embedded data in an image:
img {
height: 32px;
width: 32px;
}
<img src="data:image/svg+xml;charset=utf8,%3C?xml version='1.0' encoding='utf-8'?%3E%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='0 0 314.7 314.7'%3E%3Cstyle type='text/css'%3E .st0{fill:transparent;stroke:%23231F20;stroke-width:12;} .st1{fill:%23231F20;stroke:%23231F20;stroke-width:10;stroke-linejoin:round;stroke-miterlimit:10;} %3C/style%3E%3Cg%3E%3Ccircle class='st0' cx='157.3' cy='157.3' r='150.4'/%3E%3Cpolygon class='st1' points='108,76.1 248.7,157.3 108,238.6'/%3E%3C/g%3E%3C/svg%3E">
And here is an example of using embedded data in a web component:
function readSrc(el, url) {
var fetchHeaders = new Headers({
Accept: 'application/json'
});
var fetchOptions = {
cache: 'default',
headers: fetchHeaders,
method: 'GET',
mode: 'cors'
};
return fetch(url, fetchOptions).then(
(resp) => {
if (resp.ok) {
return resp.json();
}
else {
return {
error: true,
status: resp.status
}
}
}
).catch(
(err) => {
console.error(err);
}
);
}
class MyEl extends HTMLElement {
static get observedAttributes() {
return ['src'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
this.innerHtml = '';
readSrc(this, newVal).then(
data => {
this.innerHTML = `<pre>
${JSON.stringify(data,0,2)}
</pre>`;
}
);
}
}
}
// Define our web component
customElements.define('my-el', MyEl);
<!--
This component would go load its own data from "data.json"
<my-el src="data.json"></my-el>
<hr/>
The next component uses embedded data but still calls fetch as if it were a URL.
-->
<my-el src="data:json,[{"a":9},{"a":8},{"a":7}]"></my-el>
You can do that same this using XHR, but if your browser supports Web Components then it probably supports fetch. And there are several good fetch polyfills if you really need one.
The best advantage to using option 4 is that you can get your data from a URL and you can directly embed your data. And this is exactly how most pre-defined HTML elements, like <img> work.
UPDATE
I did think of a 5th way to get JSON data into an object. That is by using a <template> tag within your component. This still required you to call JSON.parse but it can clean up your code because you don't need to escape the JSON as much.
class MyEl extends HTMLElement {
connectedCallback() {
var data;
try {
data = JSON.parse(this.children[0].content.textContent);
}
catch(ex) {
console.error(ex);
}
this.innerHTML = '';
var pre = document.createElement('pre');
pre.textContent = JSON.stringify(data,0,2);
this.appendChild(pre);
}
}
// Define our web component
customElements.define('my-el', MyEl);
<my-el>
<template>[{"a":1},{"b":"<b>Hi!</b>"},{"c":"</template>"}]</template>
</my-el>
Passing Data Out
There are three ways to get data out of the component:
1) Read the value from a property. This is ideal since a property can be anything and would normally be in the format of the data you want. A property can return a string, an object, a number, etc.
2) Read an attribute. This requires the component to keep the attribute up to date and may not be optimal since all attributes are strings. So your user would need to know if they need to call JSON.parse on your value or not.
3) Events. This is probably the most important thing to add to a component. Events should trigger when state changes in the component. Events should trigger based on user interactions and just to alert the user that something has happened or that something is available. Traditionally you would include the relevant data in your event. This reduces the amount of code the user of your component needs to write. Yes, they can still read properties or attributes, but if your events include all relevant data then they probably won't need to do anything extra.
There is a 6th way that is really similar to #Intervalia's answer above but uses a <script> tag instead of a <template> tag.
This is the same approach used by a Markdown Element.
class MyEl extends HTMLElement {
connectedCallback() {
var data;
try {
data = JSON.parse(this.children[0].innerHTML);
}
catch(ex) {
console.error(ex);
}
this.innerHTML = '';
var pre = document.createElement('pre');
pre.textContent = JSON.stringify(data,0,2);
this.appendChild(pre);
}
}
// Define our web component
customElements.define('my-el', MyEl);
<my-el>
<script type="application/json">[{"a":1},{"b":"<b>Hi!</b>"},{"c":"</template>"}]</script>
</my-el>
If you are using Polymer based web components, the passing of data could be done by data binding. Data could be stored as JSON string within attribute of and passed via context variable.
<p>JSON Data passed via HTML attribute into context variable of and populating the variable into combobox.</p>
<dom-bind><template>
<iron-ajax url='data:text/json;charset=utf-8,
[{"label": "Hydrogen", "value": "H"}
,{"label": "Oxygen" , "value": "O"}
,{"label": "Carbon" , "value": "C"}
]'
last-response="{{lifeElements}}" auto handle-as="json"></iron-ajax>
<vaadin-combo-box id="cbDemo"
label="Label, value:[[cbDemoValue]]"
placeholder="Placeholder"
items="[[lifeElements]]"
value="{{ cbDemoValue }}"
>
<template>
[[index]]: [[item.label]] <b>[[item.value]]</b>
</template>
</vaadin-combo-box>
<vaadin-combo-box label="Disabled" disabled value="H" items="[[lifeElements]]"></vaadin-combo-box>
<vaadin-combo-box label="Read-only" readonly value="O" items="[[lifeElements]]"></vaadin-combo-box>
<web-elemens-loader selection="
#polymer/iron-ajax,
#vaadin/vaadin-element-mixin/vaadin-element-mixin,
#vaadin/vaadin-combo-box,
"></web-elemens-loader>
</template></dom-bind>
<script src="https://cdn.xml4jquery.com/web-elements-loader/build/esm-unbundled/node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js"></script><script type="module" src="https://cdn.xml4jquery.com/web-elements-loader/build/esm-unbundled/src/web-elemens-loader.js"></script>
Using a tiny lib such as Lego would allow you to write the following:
<my-element :tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>
and within your my-element.html web-component:
<template>
<table>
<tr :for="row in state.tableRowProperties">
<td>${row.p1}</td>
<td>${row.p2}</td>
</tr>
</template>
<script>
this.init() {
this.state = { tableRowPropoerties: [] }
}
</script>
I know this has been answered, but here is an approach I took. I know it's not rocket science and there are probably reasons not to do it this way; however, for me, this worked great.
This is an indirect approach to pass in data where an attribute called wc_data is passed in the custom element which is a 'key' that can be used one time.
You can obviously do whatever with the wc-data like callbacks and "callins" into the custom-tag.
link to codesandbox
files:
wc_data.ts
export const wc_data: {
[name: string]: any,
get(key: string): any,
set(key: string, wc_data: any): any
} = {
get(key: string): any {
const wc_data = this[key];
delete this[key];
return wc_data;
},
set(p_key: string, wc_data: any) {
this[p_key] = wc_data;
}
}
CustomTag.ts
import { wc_data } from './wc_data';
const template = document.createElement('template');
template.innerHTML = `
<style>
.custom-tag {
font-size: 1.6em;
}
</style>
<button class="custom-tag">Hello <span name="name"></span>, I am your <span name="relation"></span></button>
`;
class CustomTag extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
callin() {
console.log('callin called');
}
connectedCallback() {
const v_wc_data = wc_data.get(this.getAttribute('wc-data'));
console.log('wc_data', v_wc_data);
const v_name = this.shadowRoot.querySelector('[name="name"]');
const v_relation = this.shadowRoot.querySelector('[name="relation"]');
v_name.innerHTML = v_wc_data.name;
v_relation.innerHTML = v_wc_data.relation;
const v_button = this.shadowRoot.querySelector('button');
v_button.style.color = v_wc_data.color;
v_wc_data.element = this;
v_button.addEventListener('click', () => v_wc_data.callback?.());
}
disconnectedCallback() {
}
}
window.customElements.define('custom-tag', CustomTag);
console.log('created custom-tag element');
export default {};
SomeTsFile.ts
wc_data.set('tq', {
name: 'Luke',
relation: 'father',
color: 'blue',
element: undefined,
callback() {
console.log('the callback worked');
const v_tq_element = this.element;
console.log(this.element);
v_tq_element.callin();
},
});
some html..
<div>stuff before..</div>
<custom-tag wc_data="tq" />
<div>stuff after...</div>
Thanks to the other contributors, I came up with this solution which seems somewhat simpler. No json parsing. I use this example to wrap the entire component in a-href to make the block clickable:
customElements.define('ish-marker', class extends HTMLElement {
constructor() {
super()
const template = document.getElementById('ish-marker-tmpl').content
const wrapper = document.createElement("a")
wrapper.appendChild( template.cloneNode(true) )
wrapper.setAttribute('href', this.getAttribute('href'))
const shadowRoot = this.attachShadow({mode: 'open'}).appendChild( wrapper )
}
})
<ish-marker href="https://go-here.com">
...
// other things, images, buttons.
<span slot='label'>Click here to go-here</span>
</ish-marker>

Web Components, pass data to and from

My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.
JavaScript objects can obviously be sent out in the event's detail field, but what if the element needs a lot of data passed into it. Is there a way to provide it with an object in JavaScript.
What if the element for instance contains a variable number of parts that needs to be initialized or changed dynamically (e.g. a table with a variable number of rows)? I can imagine setting and modifying an attribute consisting of a JSON string that is parsed inside the component, but it does not feel like an elegant way to proceed:
<my-element tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>
Or can you make the element listen to events from the outside that contains a payload of data?
Passing Data In
If you really want/need to pass large amounts of data into your component then you can do it four different ways:
1) Use a property. This is the simplest since you just pass in the Object by giving the value to the element like this: el.data = myObj;
2) Use an attribute. Personally I hate this way of doing it this way, but some frameworks require data to be passed in through attributes. This is similar to how you show in your question. <my-el data="[{a:1},{a:2}....]"></my-el>. Be careful to follow the rules related to escaping attribute values. If you use this method you will need to use JSON.parse on your attribute and that may fail. It can also get very ugly in the HTML to have the massive amount of data showing in a attribute.
3 Pass it in through child elements. Think of the <select> element with the <option> child elements. You can use any element type as children and they don't even need to be real elements. In your connectedCallback function your code just grabs all of the children and convert the elements, their attributes or their content into the data your component needs.
4 Use Fetch. Provide a URL for your element to go get its own data. Think of <img src="imageUrl.png"/>. If your already has the data for your component then this might seem like a poor option. But the browser provides a cool feature of embedding data that is similar to option 2, above, but is handled automatically by the browser.
Here is an example of using embedded data in an image:
img {
height: 32px;
width: 32px;
}
<img src="data:image/svg+xml;charset=utf8,%3C?xml version='1.0' encoding='utf-8'?%3E%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='0 0 314.7 314.7'%3E%3Cstyle type='text/css'%3E .st0{fill:transparent;stroke:%23231F20;stroke-width:12;} .st1{fill:%23231F20;stroke:%23231F20;stroke-width:10;stroke-linejoin:round;stroke-miterlimit:10;} %3C/style%3E%3Cg%3E%3Ccircle class='st0' cx='157.3' cy='157.3' r='150.4'/%3E%3Cpolygon class='st1' points='108,76.1 248.7,157.3 108,238.6'/%3E%3C/g%3E%3C/svg%3E">
And here is an example of using embedded data in a web component:
function readSrc(el, url) {
var fetchHeaders = new Headers({
Accept: 'application/json'
});
var fetchOptions = {
cache: 'default',
headers: fetchHeaders,
method: 'GET',
mode: 'cors'
};
return fetch(url, fetchOptions).then(
(resp) => {
if (resp.ok) {
return resp.json();
}
else {
return {
error: true,
status: resp.status
}
}
}
).catch(
(err) => {
console.error(err);
}
);
}
class MyEl extends HTMLElement {
static get observedAttributes() {
return ['src'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
this.innerHtml = '';
readSrc(this, newVal).then(
data => {
this.innerHTML = `<pre>
${JSON.stringify(data,0,2)}
</pre>`;
}
);
}
}
}
// Define our web component
customElements.define('my-el', MyEl);
<!--
This component would go load its own data from "data.json"
<my-el src="data.json"></my-el>
<hr/>
The next component uses embedded data but still calls fetch as if it were a URL.
-->
<my-el src="data:json,[{"a":9},{"a":8},{"a":7}]"></my-el>
You can do that same this using XHR, but if your browser supports Web Components then it probably supports fetch. And there are several good fetch polyfills if you really need one.
The best advantage to using option 4 is that you can get your data from a URL and you can directly embed your data. And this is exactly how most pre-defined HTML elements, like <img> work.
UPDATE
I did think of a 5th way to get JSON data into an object. That is by using a <template> tag within your component. This still required you to call JSON.parse but it can clean up your code because you don't need to escape the JSON as much.
class MyEl extends HTMLElement {
connectedCallback() {
var data;
try {
data = JSON.parse(this.children[0].content.textContent);
}
catch(ex) {
console.error(ex);
}
this.innerHTML = '';
var pre = document.createElement('pre');
pre.textContent = JSON.stringify(data,0,2);
this.appendChild(pre);
}
}
// Define our web component
customElements.define('my-el', MyEl);
<my-el>
<template>[{"a":1},{"b":"<b>Hi!</b>"},{"c":"</template>"}]</template>
</my-el>
Passing Data Out
There are three ways to get data out of the component:
1) Read the value from a property. This is ideal since a property can be anything and would normally be in the format of the data you want. A property can return a string, an object, a number, etc.
2) Read an attribute. This requires the component to keep the attribute up to date and may not be optimal since all attributes are strings. So your user would need to know if they need to call JSON.parse on your value or not.
3) Events. This is probably the most important thing to add to a component. Events should trigger when state changes in the component. Events should trigger based on user interactions and just to alert the user that something has happened or that something is available. Traditionally you would include the relevant data in your event. This reduces the amount of code the user of your component needs to write. Yes, they can still read properties or attributes, but if your events include all relevant data then they probably won't need to do anything extra.
There is a 6th way that is really similar to #Intervalia's answer above but uses a <script> tag instead of a <template> tag.
This is the same approach used by a Markdown Element.
class MyEl extends HTMLElement {
connectedCallback() {
var data;
try {
data = JSON.parse(this.children[0].innerHTML);
}
catch(ex) {
console.error(ex);
}
this.innerHTML = '';
var pre = document.createElement('pre');
pre.textContent = JSON.stringify(data,0,2);
this.appendChild(pre);
}
}
// Define our web component
customElements.define('my-el', MyEl);
<my-el>
<script type="application/json">[{"a":1},{"b":"<b>Hi!</b>"},{"c":"</template>"}]</script>
</my-el>
If you are using Polymer based web components, the passing of data could be done by data binding. Data could be stored as JSON string within attribute of and passed via context variable.
<p>JSON Data passed via HTML attribute into context variable of and populating the variable into combobox.</p>
<dom-bind><template>
<iron-ajax url='data:text/json;charset=utf-8,
[{"label": "Hydrogen", "value": "H"}
,{"label": "Oxygen" , "value": "O"}
,{"label": "Carbon" , "value": "C"}
]'
last-response="{{lifeElements}}" auto handle-as="json"></iron-ajax>
<vaadin-combo-box id="cbDemo"
label="Label, value:[[cbDemoValue]]"
placeholder="Placeholder"
items="[[lifeElements]]"
value="{{ cbDemoValue }}"
>
<template>
[[index]]: [[item.label]] <b>[[item.value]]</b>
</template>
</vaadin-combo-box>
<vaadin-combo-box label="Disabled" disabled value="H" items="[[lifeElements]]"></vaadin-combo-box>
<vaadin-combo-box label="Read-only" readonly value="O" items="[[lifeElements]]"></vaadin-combo-box>
<web-elemens-loader selection="
#polymer/iron-ajax,
#vaadin/vaadin-element-mixin/vaadin-element-mixin,
#vaadin/vaadin-combo-box,
"></web-elemens-loader>
</template></dom-bind>
<script src="https://cdn.xml4jquery.com/web-elements-loader/build/esm-unbundled/node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js"></script><script type="module" src="https://cdn.xml4jquery.com/web-elements-loader/build/esm-unbundled/src/web-elemens-loader.js"></script>
Using a tiny lib such as Lego would allow you to write the following:
<my-element :tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>
and within your my-element.html web-component:
<template>
<table>
<tr :for="row in state.tableRowProperties">
<td>${row.p1}</td>
<td>${row.p2}</td>
</tr>
</template>
<script>
this.init() {
this.state = { tableRowPropoerties: [] }
}
</script>
I know this has been answered, but here is an approach I took. I know it's not rocket science and there are probably reasons not to do it this way; however, for me, this worked great.
This is an indirect approach to pass in data where an attribute called wc_data is passed in the custom element which is a 'key' that can be used one time.
You can obviously do whatever with the wc-data like callbacks and "callins" into the custom-tag.
link to codesandbox
files:
wc_data.ts
export const wc_data: {
[name: string]: any,
get(key: string): any,
set(key: string, wc_data: any): any
} = {
get(key: string): any {
const wc_data = this[key];
delete this[key];
return wc_data;
},
set(p_key: string, wc_data: any) {
this[p_key] = wc_data;
}
}
CustomTag.ts
import { wc_data } from './wc_data';
const template = document.createElement('template');
template.innerHTML = `
<style>
.custom-tag {
font-size: 1.6em;
}
</style>
<button class="custom-tag">Hello <span name="name"></span>, I am your <span name="relation"></span></button>
`;
class CustomTag extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
callin() {
console.log('callin called');
}
connectedCallback() {
const v_wc_data = wc_data.get(this.getAttribute('wc-data'));
console.log('wc_data', v_wc_data);
const v_name = this.shadowRoot.querySelector('[name="name"]');
const v_relation = this.shadowRoot.querySelector('[name="relation"]');
v_name.innerHTML = v_wc_data.name;
v_relation.innerHTML = v_wc_data.relation;
const v_button = this.shadowRoot.querySelector('button');
v_button.style.color = v_wc_data.color;
v_wc_data.element = this;
v_button.addEventListener('click', () => v_wc_data.callback?.());
}
disconnectedCallback() {
}
}
window.customElements.define('custom-tag', CustomTag);
console.log('created custom-tag element');
export default {};
SomeTsFile.ts
wc_data.set('tq', {
name: 'Luke',
relation: 'father',
color: 'blue',
element: undefined,
callback() {
console.log('the callback worked');
const v_tq_element = this.element;
console.log(this.element);
v_tq_element.callin();
},
});
some html..
<div>stuff before..</div>
<custom-tag wc_data="tq" />
<div>stuff after...</div>
Thanks to the other contributors, I came up with this solution which seems somewhat simpler. No json parsing. I use this example to wrap the entire component in a-href to make the block clickable:
customElements.define('ish-marker', class extends HTMLElement {
constructor() {
super()
const template = document.getElementById('ish-marker-tmpl').content
const wrapper = document.createElement("a")
wrapper.appendChild( template.cloneNode(true) )
wrapper.setAttribute('href', this.getAttribute('href'))
const shadowRoot = this.attachShadow({mode: 'open'}).appendChild( wrapper )
}
})
<ish-marker href="https://go-here.com">
...
// other things, images, buttons.
<span slot='label'>Click here to go-here</span>
</ish-marker>

Using React / JSX for Non-JavaScript Code Generation

I was wondering if you could use React/JSX in a code generation framework.
Is there a way to do something like the code below in JSX?
var className = "Person"
return (
//// public class {className}
//// {
////
//// }
);
Where the //// would be some special character or character sequence that signals to JSX parser that this should just be plain text?
Or is there a better approach using React that already exists?
If you're doing this in the browser you can do something like this and then grab the textContent of the <code> element that was rendered when it mounts. I haven't used React on the server but I'm guessing you could use ReactDOMSever's renderToString and then create a simple script that strips the opening and closing tags from your string and you have your code in a text string that you could save to anytype of file using node.
var data = {
class_name : 'User',
method1Name: 'doSomething'
}
class MakeClass extends React.Component {
componentDidMount(){
console.log(this.codeElem.textContent)
}
render() {
let {json} = this.props;
return (
<code ref={c=>this.codeElem=c}>{`
class ${json.class_name} {
constructor() {
// do something
}
${json.method1Name}() {
// this method does something
}
}
`}</code>
)
}
}
ReactDOM.render(
React.createElement(MakeClass, {json: data}),
document.getElementById('root')
);
You can see the full thing here:
http://jsbin.com/rizaqifasi/edit?html,js,console,output

Categories