Rendering custom html tag with react.js - javascript

What I'm trying to do is quite easy at first however I get an (obviously completely useless) error from webpack and I'm wondering how it can be fixed, I want a simple "custom" tag to be rendered by React, the code is as follows:
let htmlTag = "h" + ele.title.importance;
let htmlTagEnd = "/h" + ele.title.importance;
return(
<{htmlTag} key={elementNumber}>{ele.title.content}<{htmlTagEnd}>
);
Basically instead of having a predefined tag I want to have my own {template} tag, I know in this situation there would be work arounds for this (e.g. defining a className with my "importance" value and adding some css for that), but for the sake of science I'd like to know how (and if) this can be done in react/jsx.

JSX doesn't allow you to use dynamic HTML tags (dynamic components would work). That's because whenever you use something like <sometag ... />, an HTML element with tag name sometag is created. sometag is not resolved as a variable.
You also can't do what you have shown above. JSX expressions are not valid in place of a tag name.
Instead, you have to call React.createElement directly:
return React.createElement(
"h" + ele.title.importance,
{
key: elementNumber,
},
ele.title.content
);

Edit
My initial answer was not correct, you cannot use a variable directly and would need to use the createElement method described in Felix's answer. As noted below, and utilised in the blog post I originally linked, you can use object properties, so I've made an example of this, which hopefully will be useful as an answer to the question.
class Hello extends React.Component {
constructor() {
super();
this.state = {
tagName: "h1"
};
}
sizeChange(i) {
this.setState({
tagName: 'h' + i
});
}
changeButtons() {
var buttons = [];
for (let i=1; i<=6; i++) {
buttons.push(<button onClick={() => this.sizeChange(i)}>H{i}</button>);
}
return buttons;
}
render() {
return (
<div>
{this.changeButtons()}
<this.state.tagName>
Change Me
</this.state.tagName>
</div>
);
}
}
JSFiddle here
Original Answer
It can be done, although I don't think it is officially supported so may break in the future without warning. The caveat to this approach is that the variable name you choose for your tag cannot be the same as an HTML element.
var Demo = React.createClass({
render: function() {
const elementTag = 'h' + ele.title.importance;
return(
<elementTag>
Header x contents
</elementTag>
);
}
});
More explanation and a fuller example can be found here

Related

Get element by ID returns null

const data = [{color : "red"},{color : "blue"}, {color : "green"} ];
function libraryRoot() {
load();
return (`<div id="appDiv">
${data.map(function(value){
return `<div><p>Color ${value.color} from libraryRoot</p>`
}).join("")}
</div>
`);
}
window.onload = libraryRoot;
function load() {
let a = document.getElementById("appDiv");
console.log(a);
}
let defaultLayout = libraryRoot();
document.getElementById("root").innerHTML = defaultLayout;
<div>
<div id="root"></div>
</div>
Hi Guys i modified the script as you guys suggested, but still the return value at the first instance prints null, and then it prints the div.can you guys help me where im going wrong.
All i wanted to do is i want to call the "appDiv" id and wirte a button funcion to it. like on click {//do something}.
updated Codepen Project
You won't be able to access the element until it's written to the DOM.
Notice the word document in document.getElementById(). It's a method of the document API.
DOM stands for Document Object Model.
If you want to modify it before then then split your string literal into different pieces. Assign specific variables to important parts of the element.
Then modify them. Concatenate them back into one string and add them to the DOM.
Your code could use some comments. It's a little unclear what you're trying to do.
Here I've modified your pen to show some different ways to handle each color in your data array. You can do some conditional logic and return different template strings based on that. You could easily pass data object properties to another javascript function using the onclick attribute.
Hopefully this helps you get closer to your goal
const data = [{color : "red"},{color : "blue"}, {color : "green"} ];
function alertFunction(color) {
alert(color);
}
function libraryRoot(){
return('<div id="appDiv">' +
data.map(function(value) {
var result = `<div><p>Color ${value.color} from libraryRoot</p>`;
if (result.indexOf("red") > -1) { // checking if the div includes red
return result;
} else if (`${value.color}` == "blue") { // checking if the objects color prop includes blue
return "<p>blue</p>";
} else {
return `<button onclick="alertFunction('${value.color}')">Button with function</button>`;
}
}).join("")
+ "</div>"
);
}
window.onload = libraryRoot;
document.getElementById("root").innerHTML = libraryRoot();
<div>
<div id="root"></div>
</div>
The first issue is that you are calling load() first, which is trying to access the appDiv node that doesn't exist yet. So rethink the order on that.
The second issue is that you never actually added the appDiv content to the DOM. You can use things like document.appendChild(libraryRoot()); or something like that, though I have never injected a string as a DOM node - I use createElement for that. The link has some examples.

React add a variable name attribute

What is the cleanest way in React to add a variable name attribute?
The end result I want is: <div data-flag>Hello</div> where the name data-flag is stored in a const variable.
The ways I found now are:
const DATA_FLAG = 'data-flag';
const Hello = ({ name }) => {
const dataAttrs = { [DATA_FLAG]: true }
return <div {...dataAttrs}>Hello {name}</div>;
}
Or this one-line version (but I find it less readable):
const Hello = ({ name }) => <div {...{ [DATA_FLAG]: true }}>Hello {name}</div>;
You can play with it in this JSFiddle
These versions work fine if the attribute was variable (true or false) but in my case it's always true so I find it a bit over-killed and the syntax complex.
I would love to know if there is a cleaner way to achieve it.
I know that the best approach is to apply it directly like: <div data-flag>Hello</div> but I really need to store data-flag in a constant (as shared by other components).
You could create a React element without using the JSX syntax. Something like this should work:
const DATA_FLAG = 'data-flag'
const Hello = ({ name }) => {
const dataAttrs = { [DATA_FLAG]: true }
return React.createElement('div', dataAttrs, `Hello ${name}`)
}
This only really makes the way you're passing in the attributes look easier on the eyes though. Don't think you'll get around defining a dataAttrs object for your props.

Draft.js - CompositeDecorator: Is there a way to pass information from the strategy to the component?

Lets say my strategy calculates some numbered label. How can I pass this (e.g. via props) to the decorator component.
I know there is a props property in CompositeDecorator but how can I access it from the strategy function?
I'm a bit new to DraftJs, but based on my understanding:
Strategies should be used to identify the range of text that need to be decorated. The rendering of that decoration (which presumably includes calculating what the label should be) should be handled in the component itself, rather than the strategy.
You should be able to access the ContentState via the props object in your component, and calculate the label from that. The constructor of your component could be a good place for executing the logic for calculating the label. This also means that you might have to use a class definition for your decorator components as opposed to a pure function as shown in the examples on the draftjs website.
You can also circumvent the issue by reading the values from the text with regex. The following example is done with #draft-js-plugins:
// How the section is detected.
const strategy = (contentBlock, callback) => {
const text = contentBlock.getText();
const start = text.indexOf('<_mytag ');
const endTag = '/>';
const end = text.indexOf(endTag);
if (start !== -1 && end !== -1) {
callback(start, end + endTag.length);
}
};
// What is rendered for the detected section.
const component = ({ decoratedText }) => {
if (decoratedText) {
const label = decoratedText.match(/label="([a-zA-Z0-9/\s]*?)"/);
if (
label &&
typeof label[1] === 'string'
) {
return <div>{label[1]}</div>;
}
return null;
}
};
export const MyTagPlugin = {
decorators: [
{
strategy,
component,
},
],
};

Reduce not removing correct array item

Edit 1
Shortened the code to
removeContentNew(i) {
var contents = this.state.templateContent;
contents.splice(i, 1);
this.setState({ templateContent: contents });
}
It might have something to do with this:
componentDidMount() {
this.setState({ templateContent: this.props.template.content });
}
Still removing the wrong one on screen. When I log the state, it does give me the right array though. Maybe something wrong with the map?
--
I'm trying to bug fix this piece of code but I can't seem to find the error.
removeContent(i) {
var $formgroup = false;
const regex = new RegExp('^content.', 'i'),
contents = _.reduce(_.keys(this.refs), (memo, k) => {
if (regex.test(k) && k !== 'content.' + i) {
var $formgroup = $(this.refs[k]);
if (this.props.customer.getSetting('wysiwyg_enabled', true)) {
var html = CKEDITOR.instances['html_' + i].getData();
} else {
var html = $formgroup.find('[name="html"]').val();
}
memo.push({
subject: $formgroup.find('[name="subject"]').val(),
html: html,
text: $formgroup.find('[name="text"]').val(),
language: $formgroup.find('[name="language"]').val()
});
}
return memo;
}, []);
this.setState({ templateContent: contents });
}
i is the ID of the item I want to remove from the array templateContents. Every time I press the remove button of one of the items it always seems to delete the last one and ignores the other ones.
I've been doing some testing with the k variable and that one might be the cause of the problems, but I am not sure at all.
I'm really quite new to the RegExp way of doing things.
Any ideas how I can fix this?
Update your state in the constructor instead of inside componentDidMount method.
constructor(pops) {
super(props);
this.state = {
templateContent: this.props.template.content
}
}
Also calls to setState are async so you don't have any security when the changes is being executed
The issue was in the mapping of the array. I'll leave this here because it helped me solve my issue.
Bad (Usually)
<tbody>
{rows.map((row, i) => {
return <ObjectRow key={i} />;
})}
</tbody>
This is arguably the most common mistake seen when iterating over an
array in React. This approach will work fine unless an element is
added or removed from the rows array. If you are iterating through
something that is static, then this is perfectly valid (e.g an array
of links in your navigation menu). Take a look at this detailed
explanation on the official documentation.

Aurelia: always call method in the view (problems after upgrade)

We've upgraded Aurelia (in particular aurelia-framework to 1.0.6, aurelia-bindong to 1.0.3) and now we're facing some binding issues.
There's a list of elements with computed classes, and we had a method int the custom element that contained the list:
getClass(t) {
return '...' +
(this.selected.indexOf(t) !== -1
? 'disabled-option' :
: ''
) + (t === this.currentTag
? 'selected-option'
: ''
);
}
And class.one-way="$parent.getClass(t)" for the list element, everything was OK.
After the upgrade it simply stopped to work, so whenever the selected (btw it's bindable) or currentTag properties were modified, the getClass method just wasn't called.
I partially solved this by moving this logic to the view:
class="${$parent.getClass(t) + (selected.indexOf(t) !== -1 ? 'disabled-option' : '') (t === $parent.currentTag ? 'selected-option' : '')}"
I know that looks, well... bad, but that made t === $parent.currentTag work, but the disabled-option class still isn't applied.
So, the question is:
How do I force Aurelia to call methods in attributes in the view?
P.S.
I understand that it might cause some performance issues.
Small note:
I can not simply add a selected attribute to the list element since I don't to somehow modify the data that comes to the custom element and I basically want my code to work properly without making too many changes.
UPD
I ended up with this awesome solution by Fabio Luz with this small edit:
UPD Here's a way to interpret this awesome solution by Fabio Luz.
export class SelectorObjectClass {
constructor(el, tagger){
Object.assign(this, el);
this.tagger = tagger;
}
get cssClass(){
//magic here
}
}
and
this.shown = this.shown(e => new SelectorObjectClass(e, this));
But I ended up with this (defining an extra array).
You have to use a property instead of a function. Like this:
//pay attention at the "get" before function name
get getClass() {
//do your magic here
return 'a b c d e';
}
HTML:
<div class.bind="getClass"></div>
EDIT
I know that it might be an overkill, but it is the nicest solution I found so far:
Create a class for your objects:
export class MyClass {
constructor(id, value) {
this.id = id;
this.value = value;
}
get getClass() {
//do your magic here
return 'your css classes';
}
}
Use the above class to create the objects of the array:
let shown = [];
shown[1] = new MyClass('someId', 'someValue');
shown[2] = new MyClass('someId', 'someValue');
Now, you will be able to use getClass property:
<div repeat.for="t of shown" class.bind="t.getClass">...</div>
Hope it helps!
It looks pretty sad.
I miss understand your point for computing class in html. Try that code, it should help you.
computedClass(item){
return `
${this.getClass(item)}
${~selected.indexOf(item) ? 'disabled-option': ''}
${item === this.currentTag ? 'selected-option' : ''}
`;
}
Your code not working cause you miss else option at first if state :/
Update:
To toggle attribute state try selected.bind="true/false"
Good luck,
Egor
A great solution was offered by Fabio but it caused issues (the data that was two-way bound to the custom element (result of the selection) wasn't of the same type as the input and so on). This definitely can be fixed but it would take a significant amount of time and result in rewriting tests, etc. Alternatively, yeah, we could put the original object as some property blah-blah-blah...
Anyway:
There's another solution, less elegant but much faster to implement.
Let's declare an extra array
#bindable shownProperties = [];
Inject ObserverLocator
Observe the selected array
this.obsLoc.getArrayObserver(this.selected)
.subscribe(() => this.selectedArrayChanged);
Update the shownProperties
isSelected(t) {
return this.selected.indexOf(t) !== -1;
}
selectedArrayChanged(){
for(var i = 0; i < this.shown.length; i++){
this.shownProperties[i] = {
selected: this.isSelected(this.shown[i])
}
}
}
And, finally, in the view:
class="... ${shownProperties[$index].selected ? 'disabled-option' : '')} ..."
So, the moral of the story:
Don't use methods in the view like I did :)

Categories