Rendering react habitat components through HTML thats passed through a prop - javascript

I am currently using react habitat on a project and i have components rendering through like the following
<div data-component="MyComponent" data-prop-titl="My title"></div>
I have encountered an issue where I am trying to pass through some markup from a rich text editor that contains markup like the example above.
I want to be able to render the rich text with the react-habitat components references inside.
So the reference above can basically be passed through with the rich text and still be rendered out as a react component.
Is this possible?

Probably something like this might help
function createMarkup() {
return {__html: '<div data-component="MyComponent" data-prop-titl="My title"></div>'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
But this is a very risky practice and can expose your users to a cross-site scripting (XSS) attack

I'm the original author of React Habitat.
You are going to run into issues putting HTML into an attribute string. Its the same problem with JSON
I would just make the HTML go inside the habitat component then use the proxy variable the React Habitat sets for you.
eg
<div data-component="MyWysiwygViewer">
<h2>Some HTML text</h2>
<p>With some body</p>
</div>
In the component i would get this data with:
constructor(props) {
super(props);
const html = props.proxy.innerHTML;
}
Alternatively
you could put it inside a hidden div
<div id="myHtml" style="display: none" >
<h2>Some HTML text</h2>
<p>With some body</p>
</div>
<div data-component="MyWysiwygViewer" data-prop-html-id="myHtml" />
Then in the component i would get this data with:
constructor(props) {
super(props);
const html = document.getElementById(props.htmlId).innerHTML;
}

Related

Angular ngOnDestroy didn't fire

Demo
Demo fixed accordingly to accepted answer
Consider a component, let's call it <simple-dialog>, with this template:
<button type="button" (click)="visible = !visible">TOGGLE</button>
<div *ngIf="visible">
<ng-content select="[main]"></ng-content>
</div>
I omit the component TypeScript definition cause it's basically the same as the one generated by ng-cli.
Then I use it like this:
<simple-dialog>
<div main>
<app-form></app-form>
</div>
</simple-dialog>
When i first click the button the child component is rendered; if I click the button again the child component is removed from the DOM.
The problem is that, at this point, app-form's ngOnDestroy is not called.
I'm new to angular, so I am not sure whether my expectation is wrong.
What you are trying to achieve is called conditional content projection.
In your case, by using ng-content, the components are instantiated by the outer component, unconditionally - the inner component just decides not to display it.
If you want conditional instantiation, you should pass a template instead:
<simple-dialog>
<ng-template>
<div main>
<app-form></app-form>
</div>
</ng-template>
</simple-dialog>
and use an #ContentChild annotated property to access
the template from the content within the SimpleDialogComponent:
#ContentChild(TemplateRef, { static: false })
content!: TemplateRef<unknown>;
which can then be rendered in the template as
<div *ngIf="visible">
<ng-container [ngTemplateOutlet]="content"></ng-container>
</div>
You can also read about this here:
https://angular.io/guide/content-projection#conditional-content-projection

Global JS variable to pass HTML chunk to React component

I have a piece of HTML I need to send to a React component on page load without rendering it. I'd rather not us AJAX due to cache, but I may revert to that if I can't figure this out.
On the jsp side, I have this:
<script>window.banner_data_for_desktop = "...droplet..."</script>
This contains the HTML chunk I need to pass
<div id="desktop-top-banner">
<div>
...
</div>
</div>
On the jsx side, I've tried rendering directly like this:
<div id="top_bar">{window.banner_data_for_desktop}</div>
This renders the content, but displays the div tags as a string and not output as HTML.
So then I tried using dangerouslySetInnerHTML like this:
<div id="top_bar">dangerouslySetInnerHTML={{ __html: window.banner_data_for_desktop }}</div>
This results in an error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {__html}). If you meant to render a collection of children, use an array instead.
I've tried using Stringify, toString, creating a function to return the html like this:
function createMarkup() {
return {__html: window.banner_data_for_desktop};
}
All without any luck. If any one has a suggestion to render HTML from the global JS object, I would greatly appreciate it!
dangerouslySetInnerHtml should be an attribute of the tag:
<div dangerouslySetInnerHTML={{__html: "HTML CHUNK"}}></div>

How to pass html template as props to Vue component

I have a textarea component that include html tag and I want to get html in edit mode in this component. I use Laravel to generate html.
<template>
<div>
<textarea
:value="content"
:name="name"
:id="id">
<slot></slot>
</textarea>
</div>
</template>
In blade page I used to this component:
<my-component>
<p class="textbox">hello world</p>
</my-component>
when I put this component in page show me tag <slot></slot> in textarea. What should I do? Do you have any solution for my need?
thanks
<textarea> components are treated as static by the Vue renderer, thus after they are put into the DOM, they don't change at all (so that's why if you inspect the DOM you'll see <slot></slot> inside your <textarea>).
But even it if they did change, that wouldn't help much. Just because HTML elements inside <textarea>s don't become their value. You have to set the value property of the TextArea element to make it work.
Anyway, don't despair. It is doable, all you need to overcome the issues above is to bring a small helper component into play.
There are many possible ways to achieve this, two shown below. They differ basically in how you would want your original component's template to be.
Solution: change <textarea> into <textarea-slot> component
Your component's template would now become:
<template>
<div>
<textarea-slot
v-model="myContent"
:name="name"
:id="id">
<slot></slot>
</textarea-slot>
</div>
</template>
As you can see, nothing but replacing <textarea> with <textarea-slot> changed. This is enough to overcome the static treatment Vue gives to <textarea>. The full implementation of <textarea-slot> is in the demo below.
Alternative solution: keep <textarea> but get <slot>'s HTML via <vnode-to-html> component
The solution is to create a helper component (named vnode-to-html below) that would convert your slot's VNodes into HTML strings. You could then set such HTML strings as the value of your <textarea>. Your component's template would now become:
<template>
<div>
<vnode-to-html :vnode="$slots.default" #html="valForMyTextArea = $event" />
<textarea
:value="valForMyTextArea"
:name="name"
:id="id">
</textarea>
</div>
</template>
In both alternatives...
The usage of the my-component stays the same:
<my-component>
<p class="textbox">hello world</p>
</my-component>
Full working demo:
Vue.component('my-component', {
props: ["content", "name", "id"],
template: `
<div>
<textarea-slot
v-model="myContent"
:name="name"
:id="id">
<slot></slot>
</textarea-slot>
<vnode-to-html :vnode="$slots.default" #html="valueForMyTextArea = $event" />
<textarea
:value="valueForMyTextArea"
:name="name"
:id="id">
</textarea>
</div>
`,
data() { return {valueForMyTextArea: '', myContent: null} }
});
Vue.component('textarea-slot', {
props: ["value", "name", "id"],
render: function(createElement) {
return createElement("textarea",
{attrs: {id: this.$props.id, name: this.$props.name}, on: {...this.$listeners, input: (e) => this.$emit('input', e.target.value)}, domProps: {"value": this.$props.value}},
[createElement("template", {ref: "slotHtmlRef"}, this.$slots.default)]
);
},
data() { return {defaultSlotHtml: null} },
mounted() {
this.$emit('input', [...this.$refs.slotHtmlRef.childNodes].map(n => n.outerHTML).join('\n'))
}
});
Vue.component('vnode-to-html', {
props: ['vnode'],
render(createElement) {
return createElement("template", [this.vnode]);
},
mounted() {
this.$emit('html', [...this.$el.childNodes].map(n => n.outerHTML).join('\n'));
}
});
new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<my-component>
<p class="textbox">hell
o world1</p>
<p class="textbox">hello world2</p>
</my-component>
</div>
Breakdown:
Vue parses the <slot>s into VNodes and makes them available in the this.$slots.SLOTNAME property. The default slot, naturally, goes in this.$slots.default.
So, in runtime, you have available to you what has been passed via <slot> (as VNodes in this.$slots.default). The challenge now becomes how to convert those VNodes to HTML String? This is a complicated, still open, issue, which may get a different solution in the future, but, even if it ever does, it will most likely take a while.
Both solutions above (template-slot and vnode-to-html) use Vue's render function to render the VNodes to the DOM, then picks up the rendered HTML.
Since the supplied slots may have arbitrary HTML, we render the VNodes into an HTML Template Element, which doesn't execute any <script> tags.
The difference between the two solutions is just how they "handle back" the HTML generated from the render function.
The vnode-to-html returns as an event that should be picked up by the parent (my-component) which uses the passed value to set a data property that will be set as :value of the textarea.
The textarea-slot declares itself a <textarea>, to the parent doesn't have to. It is a cleaner solution, but requires more care because you have to specify which properties you want to pass down to the <textarea> created inside textarea-slot.
Wrapping up and off-the-shelf alternatives
However possible, it is important to know that Vue, when parsing the declared <template> into <slot>s, will strip some formatting information, like whitespaces between top-level components. Similarly, it strips <script> tags (because they are unsafe). These are caveats inherent to any solutions using <slot>s (presented here or not). So be aware.
Typical rich text editors for Vue, work around this problem altogether by using v-model (or value) attributes to pass the code into the components.
Well known examples include:
vue-ace-editor: Demo/codepen here.
Vue Prism Editor: Demo here.
vue-monaco (the code editor that powers VS Code): demo here.
vue-codemirror: Demo here. This is by far the most starred on github.
They all have very good documentation in their websites (linked above), so it would be of little use for me to repeat them here, but just as an example, see how codemirror uses the value prop to pass the code:
<codemirror ref="myCm"
:value="code"
:options="cmOptions"
#ready="onCmReady"
#focus="onCmFocus"
#input="onCmCodeChange">
</codemirror>
So that's how they do it. Of course, if <slot>s - with its caveats - fit your use case, they can be used as well.
The short answer is NOT POSSIBLE
Your slot is put inside an textarea tag. Textare tag is only able to display the text content on its box.
So in the case you want a kind of "HTML edit mode", you may looking for an WYSIWYG editor, I recommend you can use CKEditor for VueJS, the editor even will allow you to direct edit HTML code
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/vuejs.html
Your HTML
<div id="app">
<ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor>
</div>
Your Component
const app = new Vue( {
el: '#app',
data: {
editor: ClassicEditor,
editorData: '<p>Editable Content HTML</p>',
editorConfig: {
// The configuration of the editor.
}
}
} );
In your case if you want to write your own content editor you can use div with attribute contenteditable="true" rather than textarea. After this you can write your text decoration methods ...
The generated html with laravel store in myhtml and use it in vue component.
Example: I also uploaded to codesandbox [Simple Vue Editor]
<template>
<div>
<button #click="getEditorCotent">Get Content</button>
<button #click="setBold">Bold</button>
<button #click="setItalic">Italic</button>
<button #click="setUnderline">Underline</button>
<button #click="setContent">Clear</button>
<div class="myeditor" ref="myeditor" contenteditable v-html="myhtml" #input="onInput"></div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
data: () => {
return {
myhtml:
"<h1>Simple editor</h1><p style='color:red'>in vue</p><p>Hello world</p>" // from laravel server via axios call
};
},
methods: {
onInput(e) {
// handle user input
// e.target.innerHTML
},
getEditorCotent() {
console.log(this.$refs.myeditor.innerHTML);
},
setBold() {
document.execCommand("bold");
},
setItalic() {
document.execCommand("italic");
},
setUnderline() {
document.execCommand("underline");
},
setContent() {
// that way set your html content
this.myhtml = "<b>You cleared the editor content</b>";
}
// PS. Good luck!
}
};
</script>
<style scoped>
.myeditor {
/* text-align: left; */
border: 2px solid gray;
padding: 5px;
margin: 20px;
width: 100%;
min-height: 50px;
}
</style>

Manipulate dom element outside React component

I have a React component that renders HTML only on a small part of a HTML document.
From within the React component I need to replace an element, that exist outside the component, with a block of HTML.
No matter how much I'm googling this, I cannot find a straight way to accomplish this, I assume that it's because React's guidelines that naturally prescribe to use ref instead.
How would I use document.getElementById() or anything similar to insert the following sample HTML block at the place of a certain div:
<div>
<div class='yellow'>YELLOW</div>
<div class='green'>GREEN</div>
<div class='blue'>BLUE</div>
</div>
Assign an id to the top level element of the html react renders. It will still include the id attribute and thus can still be referenced with document.getElementById
<div id="toReplace">
<div className="yellow">YELLOW</div>
<div className="blue">blue</div>
<div className="red">red</div>
</div>
componentDidMount() { //or wherever
document.getElementById('toReplace').append('more html');
}
const str = "<div><div class='yellow'>YELLOW</div><div class='yellow'>GREEN</div><div class='yellow'>BLUE</div></div>"
document.getElementById('toReplace').innerHTML = "";
document.getElementById('toReplace').insertAdjacentHTML( 'beforeend', str );

How to render HTML Template and bind data from JSON response in ReactJS?

I have to render an HTML template using reactjs. HTML template is dynamic and get through an API call. There is provision in template to bind the data in html.
Sample HTML template is as follows,
<a target="_blank" href="{ad.url}">
<div class="ads temp-1">
<h2>{ad.name}</h2>
<div class="adv-content">
<div class="advs-image">
<img src="{ad.image}" />
</div>
<div class="adv-desc">{ad.description}</div>
</div>
</div>
</a>
Here ad is an Object which contains the properties url, image, name, description etc
Sample ad Object is as follows,
var ad = {
"image": "testimage.jpg",
"url": "http: //google.com",
"name": "testadvertisement",
"description": "testdescription"
}
I have achieved this in AngularJs using, $compile service.
Now I want to move this to reactjs.
I have tried to render using reactjs render function, But it didn't help. It renders html as string.
Is there any compile like function in reactjs ? Or could you please suggest any other way to do this right way ?
Any help appreciated.
As I correctly undestand you should use dangerouslySetInnerHTML prop.
For example:
// SomeComponent.js
// other methods...
render() {
// `htmlFromResponse` is your plain html string from response.
return (
<div dangerouslySetInnerHTML={{ __html: htmlFromResponse }} />
);
}
Using this prop, you can render plain html string into div element.
If you are getting html template from server, and want to pass variable to it before rendering, you can do it with Mustache package:
import Mustache from 'mustache';
// template should contain variables in {{ ... }}
const html = Mustache.render(htmlFromServer, {
variable: 'value'
});
Next, you can render output html using dangerouslySetInnerHTML prop.
create a react component which renders the HTML data, then pass your Json data as Prop to the component. this will give React element access to data and Rendered HTML will be automatically updated when Json data changes.
Check out some react tutorial video over youtube, that will give you an overview of how ReactJs works
here is how to Pass Props
https://jsfiddle.net/abhirathore2006/6a403kap/
var Hello = React.createClass({
render: function() {
console.log(this.props)
return <div>Hello {this.props.name}
<h5>{this.props.d1.name}</h5>
id:{this.props.d1.id}
</div>;
}
});
ReactDOM.render(
<Hello name="World" d1={{"name":"test","id":"5"}} />,
document.getElementById('container')
);

Categories