How to convert a string into React element- ReactJs/ Javascript - javascript

I crated a react html element like:
let elements = (
<div>
<div>dwewe</div>
<div>wefwef</div>
<span>yurhfjer</span>
</div>
);
and now I wanted to pass this to an html attribute, hence I converted the react element into string using:
<span data-tip-react={ReactDOMServer.renderToString(element)}>{title}></span>
I'm now able to access these elements, however I'd like to convert it back to react element (the way it was before conversion)
here is what I'm expecting the o/p as:
I tried using DOMParser, however it returned an html element that React did not accept for rendering and threw an errr: not a react element
How do I convert the string back into the same format - React element??
please help!
thanks

Following here :
dynamic HTML String to react component
You can use dangerouslySetInnerHTML (for simple element) or some npm package :
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
getDom() {
return (
<div>
<div>dwewe</div>
<div>wefwef</div>
<span>yurhfjer</span>
</div>
);
}
convertToString(dom) {
console.log("To String", ReactDOMServer.renderToString(dom))
return ReactDOMServer.renderToString(dom)
}
convertToDOM(string) {
let domparser = new DOMParser();
console.log("To Dom", domparser.parseFromString(string, 'text/html'))
return domparser.parseFromString(string, 'text/html')​​
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
{<div dangerouslySetInnerHTML={{__html: this.convertToString(this.getDom())}}></div>}
</p>
</div>
);
}
}
ex : https://stackblitz.com/edit/react-mhsqfd

Related

How to inject data in a html string in React?

I have a html string that contains a link. I need to add the attribute rel="noopener" for security purposes. The html string is injected through dangerouslySetInnerHtml:
const Component = ({ message }) => {
return (
<div>
<div dangerouslySetInnerHTML={{ __html: message }} />
<div>
);
};
The string looks like: Hello check out this page
So the desired output would be: Hello check out this page
How to do it?
Try this:
const Component = ({ message }) => {
function secureATags(html) {
// Parse HTML
let doc = (new DOMParser()).parseFromString(html, "text/html")
// Append attribute
doc.querySelectorAll('a').forEach(entry => {
entry.setAttribute('rel', 'noopener')
})
// Reserialize to HTML
return doc.body.innerHTML
}
return (
<div>
<div dangerouslySetInnerHTML={{ __html: secureATags(message) }} />
<div>
)
}
I would use the Browser DOM to achieve this, as follows:
const div = document.createElement("div");
div.innerHTML = 'Hello check out this page';
div.childNodes[1].setAttribute("rel", "noopener");
console.log(div.innerHTML);
If the actual HTML text is more complex than in your example, then div.childNodes[1] will need to be replaced with code that looks for and selects the proper node. But even then (or especially then?), this is probably the easiest and most reliable way to achieve your goal.
Direct use of setDangerousInnerHtml is strictly not recommended due to security issues.
you can use a plugin on npmjs.org pkgname: React-html-parser for injecting the html safely
Maybe consider using a function or component that puts it all together based on the data you send in? E.g.
function App() {
const linkBuilder = (textBefore, linkText, textAfter, href) => {
return (
<div>
{textBefore}
<a href={href} target="_blank">
{linkText}
</a>
{textAfter}
</div>
);
};
return (
<div>
{linkBuilder("Hello check out ", "this page", "", "www.google.com")}
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Also according to this you don't need rel=noopener anymore if you use target="_blank". But if it's necessary you can pass it in as a boolean and apply it on the function/component side.

Dynamically made strings for id in JSX

I want to make id like this dynamically.
<div id="track_1"></div>
<div id="track_2"></div>
So I gave the id like this from parent component.
export default function Components(props) {
return (
<AudioTrack trackNum="1"/>
<AudioTrack trackNum="2"/>
)
}
then in my AudioTrack Component I got the trackNum and want to use like this
const AudioTrack = (props) => {
return(
<div id="track_{props.trackNum}" ></div>
);
}
Howeber it doesn't work.
Is there any good way?
Since the div prop isn't a constant string, you need {} to indicate an expression, and then either use + to concatenate or a template literal with ${}:
<div id={`track_${props.trackNum}`}></div>

How to inject a dinamically created element into an existing div in React JSX?

I have a list of objects photos, from a json data file, that I would like to organize into 3 different <div> columns, but I dont know how to achieve that, here is my broken non-optimized code:
<div className="container">
<div ref={leftColRef} className="left-col" />
<div ref={centreColRef} className="centre-col" />
<div ref={rightColRef} className="right-col" />
{Object.keys(photos).forEach((n, i) => {
const id = photos[n].id;
const thumb = photos[n].thumbnailUrl;
const title = photos[n].title;
const element = (
<Thumbnail id={id} title={title} thumb={thumb} />
);
if (i % 3 === 0) {
leftColRef.current.append(element);
} else if (i % 3 === 1) {
centreColRef.current.append(element);
} else {
rightColRef.current.append(element);
}
// this line works, it idsplays the data but is commented as the data needs to go inside its respective columns
// return <Thumbnail key={id} title={title} thumb={thumb} />;
})}
</div>
The idea is to insert some elements into the left-column when i%3 = 0 and others in the centre-column when i%3 = 1 and so on ...
And a link to my codesandbox
Any help/advise will be much appreciated.
Easiest is probably to prepare the data outside the render function and to render the column one by one.
You should not manipulate the DOM like it's done in jQuery using JSX
Example:
const Component = (props) => {
const filterPhotos = (column) => {
return props.photos.filter((photo,index)=> index%3==column);
}
return <>
<MyColumn photos={filterPhotos(0)}/>
<MyColumn photos={filterPhotos(1)}/>
<MyColumn photos={filterPhotos(2)}/>
</>;
}
First, using ref on div to inject stuff on it is wrong. It's the opposite of how react works.
Like charlies said, I would split the photos in 3 different arrays before the render. Then, you'll be able to do something like this :
<div ref={leftColRef} className="left-col" />
{ photosLeft.map(photo => <Thumbnail key={photo.id} {...photo} />)
</div>
when preparing your data, try to use the same object properties and component props name so you can spread it easily ( {...photo} ).
Note: Also, when rendering an array in react, each child must have a unique key props. It will help react to render on that part of dom if your data change.

can i use pug (ex-jade) with react framework?

i have read some of pug documentation. its said that i have to install pug first and i'm already done that. then i have to require pug in my js file.
but i don't know where to write the compile for pug file in my react files? what is the right steps to use pug in react framework?
thanks! i really appreciated any help.
here is one of my component in react that i would like to render it with pug.
import React from 'react';
import Sidebar from './Sidebar';
import Header from './header/Header';
import {tokenverify} from '../../utils/helpers';
import pug from 'pug';
class Home extends React.Component {
componentDidMount() {
const token = localStorage.getItem('token')
tokenverify(token)
.catch((res) => {
this.props.history.push('/')
})
}
render() {
return(
<div className="main-container">
<div className="col-md-1">
<Sidebar history={this.props.history} username={this.props.params.username}/>
</div>
<div className="col-md-11">
<div className="row">
<Header history={this.props.history} username={this.props.params.username} />
</div>
<div className="row">
{this.props.children}
</div>
</div>
</div>
)
}
}
export default Home
I found this project in very early phase of its development : https://github.com/bluewings/pug-as-jsx-loader.
I like it because it lets me write my dumb (presentational) react components as pug templates.
The only JSX functionality it currently supports are iterating and conditional if. Which seems good enough for writing most of the dumb components.
Here are the steps to use it
1. Install pug-as-jsx-loader
npm install pug-as-jsx-loader --save-dev
For next step you will have to eject if you are using create-react-app
2. Tell webpack how to handle pug templates.
In your webpack.config.dev.js,
{ test: /\.pug$/, use: [require.resolve('babel-loader'), require.resolve('pug-as-jsx-loader')] },
3. Import pug template in your component
import myTemplate from './mycomponent.pug'
4. Return compiled template from render function
const MyComponent = ({someProperty, someOtherProperty})=> {
return myTemplate.call({}, {
someProperty,
someOtherProperty
});
};
5. Define a pug to render component
#my-element
ul.my-list
li(key='{something.id}', #repeat='something as someProperty')
div(className='planet') {something.name}
div(className='vehicle') {something.type}
div(className='overview') {something.cost}
div(className='cancel', onClick='{()=> someOtherProperty(something)}')
div(className='no-mobile fa fa-remove')
A read about my experience : https://medium.com/p/7610967954a
With Pug, you have two options: render template to HTML string, passing the data object right away or render template to an efficient javascript function that outputs html when passed a data object.
When using pug(alone) with dynamic data, the choice is obviously to compile to function, so that data can be applied on the client.
However, React does not actually consume, or send to the client, html.
If you read an explanation of JSX, you will see that it is just HTML-lookalike syntactic sugar that gets compiled to a javascript function that programmatically creates DOM nodes (essential for the way React handles diffing and updating the page). Pug at the moment, even on the client, outputs an HTML string. Hence, the only way we will be able to use it is
dangerouslySetInnerHTML as following:
//from https://runkit.io/qm3ster/58a9039e0ef2940014a4425b/branches/master?name=test&pug=div%20Wow%3A%20%23%7Ba%7D%23%7Bb%7D
function pug_escape(e){var a=""+e,t=pug_match_html.exec(a);if(!t)return e;var r,c,n,s="";for(r=t.index,c=0;r<a.length;r++){switch(a.charCodeAt(r)){case 34:n=""";break;case 38:n="&";break;case 60:n="<";break;case 62:n=">";break;default:continue}c!==r&&(s+=a.substring(c,r)),c=r+1,s+=n}return c!==r?s+a.substring(c,r):s}
var pug_match_html=/["&<>]/;
function pug_rethrow(n,e,r,t){if(!(n instanceof Error))throw n;if(!("undefined"==typeof window&&e||t))throw n.message+=" on line "+r,n;try{t=t||require("fs").readFileSync(e,"utf8")}catch(e){pug_rethrow(n,null,r)}var i=3,a=t.split("\n"),o=Math.max(r-i,0),h=Math.min(a.length,r+i),i=a.slice(o,h).map(function(n,e){var t=e+o+1;return(t==r?" > ":" ")+t+"| "+n}).join("\n");throw n.path=e,n.message=(e||"Pug")+":"+r+"\n"+i+"\n\n"+n.message,n}function test(locals) {var pug_html = "", pug_mixins = {}, pug_interp;var pug_debug_filename, pug_debug_line;try {;var locals_for_with = (locals || {});(function (a, b) {;pug_debug_line = 1;
pug_html = pug_html + "\u003Cdiv\u003E";
;pug_debug_line = 1;
pug_html = pug_html + "Wow: ";
;pug_debug_line = 1;
pug_html = pug_html + (pug_escape(null == (pug_interp = a) ? "" : pug_interp));
;pug_debug_line = 1;
pug_html = pug_html + (pug_escape(null == (pug_interp = b) ? "" : pug_interp)) + "\u003C\u002Fdiv\u003E";}.call(this,"a" in locals_for_with?locals_for_with.a:typeof a!=="undefined"?a:undefined,"b" in locals_for_with?locals_for_with.b:typeof b!=="undefined"?b:undefined));} catch (err) {pug_rethrow(err, pug_debug_filename, pug_debug_line);};return pug_html;}
// pug source: "div Wow: #{a}#{b}"
// this would obviously be much shorter if you include pug-runtime globally in your application
function createMarkup(a,b) {
return {__html: test({a:a,b:b})};
}
function MyComponent(props) {
return <div dangerouslySetInnerHTML={createMarkup(props.a, props.b)}/>;
}
ReactDOM.render(
<MyComponent a="banana" b="&patata"/>,
document.getElementById('root')
)
<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=root />
Alternatively, there are attempts to translate jade or pug syntax into react directly, such as pug-react-compiler and babel-plugin-transform-pug-to-react. It seems they solved including further react components inside the pug template, which might be a desirable tradeoff for them possibly having quirks.

render html string to React component via custom parsing

I have a html string fetched from server which looks like this:
<h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p>
Now I want to transform the html with <img class="cover" src="someimg.jpg"> part converted to my own React Component <LazyLoadImg className="cover" src="someimg.jpg" />.
Without server rendering or dangerouslySetInnerHTML, how do I do that?
Your HTML string.
let responseText = '<h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p>';
Splitting the string by line breaks.
let splitter = /\n/;
let broken = responseText.split(splitter);
From here, it's a pretty simple task to strip out tags to get the stuff you really need.
broken[0] = broken[0].slice(4, broken[0].length - 5);
broken[1] = broken[1].slice(24, broken[1].length - 3);
broken[2] = broken[2].slice(3, broken[2].length - 4);
Boom.
console.log(broken); // [ 'Title', 'someimg.jp', 'Introduction' ]
Make sure all the above logic ends up in the right place within your component. I'm assuming that you received the original string via AJAX call. Probably put all that stuff in the callback.
Here's your component.
class ProfileSection extends React.Component {
constructor(props) {
super(props);
}
state = {
}
render () {
return (
<div>
<h1>{broken[0]}</h1>
<LazyLoadImg className="cover" src={broken[1]} />
<p>
{broken[2]}
</p>
</div>
);
}
}

Categories