True custom attributes (e.g. Microdata) in React - javascript

The site I am developing makes use of Microdata (using schema.org). As we are shifting development over to use React to render our views I have hit a blocker where React will only render attributes in the HTML spec however Microdata specifies custom attributes such as itemscope.
As I'm relatively new to React and haven't had chance to fully understand the core just yet, my question is what would be the best way to extend the functionality of react.js to allow for defined custom attributes, e.g., Microdata?
Is there a way of extending the attributes/props parser or is it a job for a mixin which checks all passed props and modifies the DOM element directly?
(Hopefully we'll be able to put together a drop in extension for everyone to provide support for this when a solution is clear.)

You can also use "is" attribute. It will disable the attribute white-list of React and allow every attribute. But you have to write class instead of className and for instead of htmlFor if you use is.
<div is my-custom-attribute="here" class="instead-of-className"></div>
Update React 16 custom attributes are now possible
In react 16 custom attributes are now possible
React 16 custom attributes

It looks like these non-standard properties have been added to React
itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
Note that properties have capital letter in the middle:
<div itemProp="whatever..." itemScope itemType="http://schema.org/Offer">
will generate proper lowercase attributes as result.

You should be able to do it with componentDidMount:
...
componentDidMount: function() {
if (this.props.itemtype) {
this.getDOMNode().setAttribute('itemscope', true)
this.getDOMNode().setAttribute('itemtype', this.props.itemtype)
}
if (this.props.itemprop) {
this.getDOMNode().setAttribute('itemprop', this.props.itemprop)
}
}
...
The whole check for Microdata attributes can be wrapped into a mixin for convenient. The problem with this approach is that it won't work for built-in React component (components created by React.DOM). Update: Looking closer at React.DOM, I come up with this http://plnkr.co/edit/UjXSveVHdj8T3xnyhmKb?p=preview. Basically we wrap the built-in components in a custom component with our mixin. Since your components are built upon React 's built-in DOM components, this would work without you having to include the mixin in the components.
The real solution would be injecting a custom config instead of React's DefaultDOMPropertyConfig, however I can't find a way to do so in a drop-in manner (DOMProperty is hidden by the module system).

For those who's still looking for answers:
https://facebook.github.io/react/docs/tags-and-attributes.html
Example:
<div itemScope itemType="http://schema.org/Article"></div>

So far, the best method I've found is based off of some Amp interop code linked from a comment on react's bug tracker thread on the subject. I modified it slightly to work with a newer version of React (15.5.4) and TypeScript.
For regular ES6, you can just remove the type annotation for attributeName. Using require was needed in TS since DOMProperty isn't exposed in react's index.d.ts, but again import could be used in regular ES6.
// tslint:disable-next-line:no-var-requires
const DOMProperty = require("react-dom/lib/DOMProperty");
if (typeof DOMProperty.properties.zz === "undefined") {
DOMProperty.injection.injectDOMPropertyConfig({
Properties: { zz: DOMProperty.MUST_USE_ATTRIBUTE },
isCustomAttribute: (attributeName: string) => attributeName.startsWith("zz-")
});
}
Now you can use any attribute starting with zz-
<div zz-context="foo" />
Normally it'd be a bad idea to use internal parts of react like this, but I think it is better than any of the other methods. It works the same way as existing open-ended attributes like data- and the JSX is even type safe in TS. I believe the next major version of react is going to do away with the whitelist anyway, so hopefully changes won't be needed before we can remove this shim entirely.

Related

Setting global properties by calling imported javascript functions in QML

I use the Universal style for my QtQuick app and I want to provide a ColorDialog for adjusting the accent color.
I have something like this:
ColorDialog {
id: accChooser
title: "Please choose a color"
onAccepted: {
setGlobalAccentColor(accChooser.color)
}
}
*Note that I cannot simply write Universal.accent=... inside a child item because it has no effect on the parent.See this.
and this function:
function setGlobalAccentColor(accentColor){
Universal.accent = accentColor
}
It works when the function setGlobalAccentColor is defined within the same QML file as accChooser,but if I define that function inside an external JS file (say helpers.js) and import it via:
import "helpers.js" as JSHelpers
and use it this way:
ColorDialog{
...
JSHelpers.setGlobalAccentColor(colorDialog.color)
...
}
it doesn't work.There's no specific error or warning message in the output of the app.
Thanks.
May be it is required to import the universal style in the javascript file.
The documentation universal style says below (look in dependency section)
The Universal style must be separately imported to gain access to the
attributes that are specific to the Universal style
You can try importing as said below into your javascript (helpers.js) file.
.import QtQuick.Controls.Universal 2.12 as JsUniversal
And then try accessing (like example: JsUniversal.accent..).
Note that I cannot simply write Universal.accent=... inside a child item because it has no effect on the parent.See this.
While setting it to the child won't affect your whole application, you can set it directly to the whole window.
Window.window.Universal.accent = accentColor;
Universal is an attached object, you can attach it to an abitrary object, not just the current one, by doing <object>.<AttachingType>.
We attach it to the parent window by accessing the window via another attached property: Window.window.

How can I access native HTML attributes in stenciljs? And how to make it appear in the documentation?

The web components made with stenciljs don't extend HTMLElement. How can I access the native attributes and use them in my component, say the title attribute? When I add #Prop() title and use it in my template an error is shown.
Adding #Prop() also makes the attributes visible in the generated documentation. How can I add the used or required native attributes to the generated documentation?
Compiler error I'm getting:
The #Prop() name "title" is a reserved public name. Please rename the "title" prop so it does not conflict
with an existing standardized prototype member. Reusing prop names that are already defined on the element's
prototype may cause unexpected runtime errors or user-interface issues on various browsers, so it's best to
avoid them entirely.
Yes, you are not allowed to do so but you can pass HTML attributes directly to the element without declaring them with the #Prop decorator. In your case, just pass title to your component.
<your-component title="test title"></your-component>
Then, if you would like to read the value of your title attribute, you have to get the reference to the host element first.
#Element() host: HTMLElement;
Then, you can read it with your host element's getAttribute method, for instance:
componentDidLoad() {
const title = this.host.getAttribute('title');
console.log(title); // or do something with it
}
#Prop() is like reading from tag to component
#Prop({"reflectToAttr": true}) will keep a two way binding and updates both - tag to component & component to tag
It's important to know that you are not allowed to update your #Prop variables inside the component until you specifically allow it with the mutable property. #Prop({"mutable": true})
If you want both just use comma seperated syntax like:
#Prop({"mutable": true, "reflectToAttr": true})
For details please go here:
https://stenciljs.com/docs/properties
I faced sometimes some issues using the native attributes like "title", "focus" and so on. The correct way would be using "data" before the attribute like "data-title", "data-focus" and in the component #Prop() dataTitle, #Prop() dataFocus.
But to be honest i don't like that the developer using the web-components have to learn a web-component specific syntax so i use the native attributes anyway. Which results sometimes in some errors that you can fix easily. But this would be a topic for another question.
#Update
I just realized that in newer StencilJS versions is just #Prop({"reflect": true}) but the idea is still the same

Vaadin elements vaadin-grid custom renderer in API 2+

I'm almost done in porting a couple of projects based on vaadin elements
vaadin-grid
from API 1.x to the latest version but I've not found examples or documentation about how to assign a custom renderer to a column.
For example in main.js I can't figure out how to port in API 2+ the following:
grid.columns[2].renderer = function (cell) {
cell.element.innerHTML = '';
var progressBar = document.createElement('progress');
progressBar.setAttribute('value', ((statuses.indexOf(cell.data) + 1) / statuses.length).toString());
cell.element.appendChild(progressBar);
};
The specific problem in here is that in API 2+ columns are undefined
Is it possible to assing custom rendering behavoir to a vaadin-grid-column?
NB: this question is not about vaadin framework but about vaadin elements
Debug session looking for something may help such as TemplateRenderer or similar but I found nothing until now:
The JS API is significantly changed from v1 to v2, and there’s no longer a columns object. Instead, if you want to configure columns using JS, you need to modify the properties of the <vaadin-grid-column> elements directly (you need to have a DOM reference).
For renderers specifically, you use regular HTML in the column template, as mentioned in the migration guide (the Wiki was closed for some reason, I just reopened it).
For your specific code example, it would translate to:
<vaadin-grid>
<vaadin-grid-column>
<template>
<progress value="[[item.value]]"></progress>
</template>
</vaadin-grid-column>
</vaadin-grid>
Replace item.value with the correct property in your data object (or use a computed property if you need to transform the data somehow before passing it onto the <progress> element.
Bonus:
Have you considered using <vaadin-progress-bar> ;)
Valo theme demo: https://cdn.vaadin.com/vaadin-valo-theme/2.0.0-alpha4/demo/progress-bars.html

React.js Dataflow Paradigm - how are data.props, state, and JSX beneficial?

I'm using React and created a small page that has 4 components (React classes, what is the preferred term? I'll call them components in this post):
Component Breakdown
a parent "App" component that includes and manages the other components
a "Form" component that lets the user interact with the page
a "String View" component that displays the input from the form as text
a "Visual View" (I know, bad name...) component that interprets the string view and performs actions to adjust the visual.
Dataflow
The communication of these components using states and props is as follows:
The Form has onChange handlers that pass the new state to the App
The App funnels the state data to the String View
The String View updates and passes the updated state to the App
The App funnels the new state data to the Visual View
Finally, the Visual View now updates based on the new state.
Sample Code
var App = React.createClass({
handleFormChange: function(formData) {
this.setState({formData:formData});
},
handleStringChange: function(stringData) {
this.setState({stringData:stringData});
},
render: function() {
return (
<div className="app">
<FormView onFormChange={this.handleFormChange}/>
<StringView formData={this.state.formData} onStringChange={this.handleStringChange}/>
<VisualView stringData={this.state.stringData}/>
</div>
);
}
});
var FormView = React.createClass({
handleFormChange: function(e) {
this.props.onFormChange(e.target.value);
}
render: function() {
return(
<div className="formView">
<select onChange={this.handleFormChange}>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
);
}
});
var StringView = React.createClass({
componentDidUpdate: function() {
this.props.onStringChange({newString:'newStringState'});
},
render: function() {
this.props.formData;
// process formData and update state
return (
<div className="stringView">
{this.props.formData}
</div>
);
}
});
var VisualView = React.createClass({
render: function() {
var selection = this.props.stringData,
output = '';
if (selection === 1) {
output = 'Hooray, 1!';
} else {
output = 'Yes! 2!';
}
return (
<div className="stringView">
{output}
</div>
);
}
});
Questions
Is this the correct dataflow paradigm that React is trying to enforce (components only talk to parents, not siblings)?
Compared to how I would have written this in just regular JavaScript, this seems terribly constrained. Am I missing the big picture? Is this dataflow paradigm designed to prevent future problems (if so, which ones? Any that can't be solved with disciplined regular JavaScript?), or is there some other purpose that I'm missing?
I'm getting a lot of repeated function names (handleFormChange for example, it's used in App and Form View), is there a good way to make these distinguishable? Or, are repeated function names across components desirable?
When the components actually build, the JSX stuff gets transpiled down into real JavaScript. Is there an advantage to using JSX? Would writing components in the already transpiled JavaScript have an advantage?
To start, I think it is ok to call "components", and I've seen lot of people call that way. I will answer your questions below, in an order that I think is better to make my answers make sense.
When the components actually build, the JSX stuff gets transpiled down into real JavaScript. Is there an advantage to using JSX? Would writing components in the already transpiled JavaScript have an advantage?
JSX kinda mixes JavaScript and HTML, so, it makes your code "friendly". You will create your components, and just "call" them as HTML tags. Below you can see the difference between writing JSX and pure JavaScript.
return <div className="my-component"><p>Awesome</p></div>;
return ReactDOM.div({
className: 'my-component'
}, ReactDOM.p({}, "Awesome"));
I don't know you, but I would get tired to write this amount of code just to render a div with a paragraph.
You can check more benefits of using it here:
https://hchen1202.gitbooks.io/learning-react-js/content/benefits_of_jsx.html
I'm getting a lot of repeat function names (handleFormChange for example, it's used in App and Form View), is there a good way to make these distinguishable? Or, are repeated function names across components desirable?
It is not bad, also, your app is a "demo" one, if it would be a "real" one, it would have some better names for the components (i.e. <FormView> would be <ContactForm>) and maybe your method names would be different. But it is not bad at all. For example, inside <ContactForm> you may call the submit handler as onSubmit, but outside (the prop that you pass), you may call onContactFormSubmit, or, in a more semantic way, onContactFormFilled.
If your application starts to grow and you have lots of things repeated in the same component (that is the case of your <App>), you may try to split your components, therefore, each of your component will "know" about a "domain", and it would not appear to have lots of repeated stuff.
Is this the correct dataflow paradigm that React is trying to enforce (components only talk to parents, not siblings)?
First of all, React doesn't "enforce" anything, as some people say, React is the "v" in MVC, so, you have your "presentation" layer described as components, and the data may flow in the way you want.
But you got a point when you say "components only talk to parents, not siblings", because that is the way you can "communicate" between your components when you have multiple components. Since a component can't see its sibling, you need someone to orchestrate this communication, and, in this case, this is the parent's job.
There are other ways to make components "talk" to each other (i.e. using refs), but having a parent to orchestrate is, IMO, the most reliable (and better testable) one.
Compared to how I would have written this in just regular JavaScript, this seems terribly constrained. Am I missing the big picture? Is this dataflow paradigm designed to prevent future problems (if so, which ones? Any that can't be solved with disciplined regular JavaScript?), or is there some other purpose that I'm missing?
I decided to answer that as the last one, to sum up some things.
IMO, React is just great, you start to have your "logic" in the right place (a component), and you can just compose things in order to make your page work well (and by well I mean it is orchestrated correctly).
React also makes it easier to "think" about how you will build your interfaces. This Pete Hunt's blog post is amazing, and you should check it out:
https://facebook.github.io/react/docs/thinking-in-react.html
If you would be writing your code with plain JavaScript, you would have to handle DOM in some way (i.e. using a template engine) and your code would end up mixing DOM manipulation with your application logic. React just abstracts that for you. You can only care about presenting stuff. Another advantage is that, when everything is a component, you can reuse those components, it doesn't matter where they are located. If you pass the props correctly, your component will work as expected.
I know it seems exhaustive to write those components, but as you start to write more components you start to see lots of benefits. One of them is to nevermore wonder about how to present your data (no more concatenating HTML strings or calling template functions). Another one is that it is easy to "split" your interfaces, what makes your code easier to maintain (and that is not straightforward when using plain JavaScript).
To be honest, this application you wrote is really simple, and you may not see lots of advantages of using React for building it. I think you should try to create a more "complex" one, and compare it with plain JavaScript. By "complex", I mean "user interface" complex. For example, create a form that allows user to submit multiple "people". And "people" should have "name" and multiple "pet" (which also have a name). You will see how hard is it to handle "add" and "remove" operations in this case, and how easy React handle that kind of thing.
I think that is it, I hope you and React "click". It changed my mind about how to create complex user interfaces.

Bindings on self-written HandlebarsHelper?

i am trying add internationalization-abilities to my website.
I have written my own I18n.js which uses translation-objects out of the DS.store instead of its own (so there is a translation model and Ember preloads it on Application-start).
To get my translations into the Templates i have written this handlebars-helper
Ember.Handlebars.registerHelper('i18n', function(key) {
return Application.I18n.t(key);
});
so i could easily use it like:
{{i18n example_key}}
So far, everything works just perfect.
But the translations visible on screen are not bind to its translation-models.
If i change a translation in the administration-page which is places there too, i have to reload the page.
is it possible to add bindings between the helper and the translation model the helper have to display?
Thanks
Use registerBoundHelper instead of registerHelper. I don't even think registerHelper is part of the public API.
What does Application.I18n look like exactly? In order to make the {{i18n}} helper refresh its content when something changes, it needs to observe something that is observable.
Ember.Handlebars.helper is useful if you pass an object with observable properties (see http://emberjs.com/guides/templates/writing-helpers/#toc_dependencies). But if you only pass a key as a string, you'll have to set up the binding yourself in some way.

Categories