I want to write other languages code in react js - reactjs

I am working on building a website.
I made all things, but now I'm stuck in adding code to the website.
I want to put some codes inside the JSX component but it is having some problems with adding { <<these types of symbols.
Is there any way I can write the C++ code or C code inside the react element?
import React from 'react'
const Template = () => {
return (
<div>
<h1></h1>
</div>
)
}
export default Template

The JSX won't appreciate the "{ <<", but if you want a quick in on this, you may try something like this -
const SomeCode = ()=><code>{`#include <stdio.h>;`}</code>
That might not be sufficient - you may need proper highlighting with specific programming language, formatting, etc. for what you might be building. But just for getting literals such as << working with JSX - you may take the above example as base.

In JSX, which is what react usees, brackets will be parsed.
Therefore, strings should be inside {`content`}, or you can define that code as a string, and place it inside jsx as below
const SomeComponent = ()=>{
const codeSnippet = `{ << whatever code blahblah`
return <div>
{codeSnippet}
</div>
}

Related

React-Intl pass translation as string variable and not object

I'm in the process of adding react-intl to a payment app I'm building but hitting a snag. I apologize if this has been addressed somewhere. I scoured the issues and documentation and couldn't find a direct answer on this (probably just overlooking it).
Use Case: Once a payment is processed I'd like to give the user the option to tweet a translated message indicating they've donated.
Problem: Twitter uses an iframe to "share tweets", and requires a text field as a string variable. When I pass my translation I get [object Object] in the tweet instead of the translated text. This makes sense based on my understanding of the translation engine. But I cant seem to find a way to pass a string rather than a translation object.
what I get when I use {translate('example_tweet')}
const translationText = object
what I need
const translationText = 'this is the translated text'
Question
How do I get the translated text as a string variable rather than an object to be rendered on a page?
Code
button
import { Share } from 'react-twitter-widgets'
import translate from '../i18n/translate'
export default function TwitterButton () {
return (
<Share
url='https://www.sampleSite.org' options={{
text: {translate('example_tweet')},
size: 'large'
}}
/>
)
}
translate
import React from 'react'
import { FormattedMessage } from 'react-intl'
const translate = (id, value = {}) => <FormattedMessage id={id} values={{ ...value }} />
export default translate
I was able to solve it without messing with react-intl. I built a function that scrapes the text I need from the page itself. So it really doesnt matter what the language is. I was hoping to figure out how to snag the translations as variables, but this gets the job done.
function makeTweetableUrl (text, pageUrl) {
const tweetableText = 'https://twitter.com/intent/tweet?url=' + pageUrl + '&text=' + encodeURIComponent(text)
return tweetableText
}
function onClickToTweet (e) {
e.preventDefault()
window.open(
makeTweetableUrl(document.querySelector('#tweetText').innerText, pageUrl),
'twitterwindow',
'height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0'
)
}
function TwitterButton ({ text, onClick }) {
return (
<StyledButton onClick={onClick}>{text}</StyledButton>
)
}

Create Html from React Component including Style

I have a simple react component in which using ref I am getting the div but I have to generate a html includes styling as well. So I can pass this html to PDF generation backend server.
pdfRef(elem){
console.log(elem);
//<div><span>dataPDF</span> </div>
}
render() {
return (
<div ref={(elem) => this.pdfRef(elem)} className="SomeCssClass">
<span >dataPDF</span>
</div>
);
}
}
[Edit]
When I try to print the div via ref, the elements are printed with class name. But when I send this string to pdf service, since only html element is sent and class name without the actual css , the pdf is generated without style.
is there any way to generate html with css as as string so further it can be send to pdf service. Hope the question is clear
Any pointers?
The server.js script in react-dom lets you render a React component to static html string. You can require it in your code like:
const ReactDOMServer = require('react-dom/server');
Or using ES6 syntax:
import ReactDomServer from 'react-dom/server'
After this you can render your component to HTML string using the ReactDomServer.renderToString or ReactDomServer.renderToStaticMarkup functions as follows:
const htmlStr = ReactDomServer.renderToStaticMarkup(<MyComponent prop1={'value1'} />);
This looks almost exactly like ReactDom.render, except that it doesn't need the second parameter of dom node to render at, and the html string is returned. Additionally this method can be used on both client and server side. For your generate-pdf use case renderToStaticMarkup would suffice. If required check the documentation at following link for subtle difference between the two methods mentioned above: https://reactjs.org/docs/react-dom-server.html

How to render a HTML string in React?

I have a string like < b >hi< /b >. I have to render it as "hi". Can someone let me know an equivalent thing like innerHTML in Angular that I can use in React?
you can try dangerouslySetInnerHTML with the enclosing tag:
<div dangerouslySetInnerHTML={{ __html: yourhtml }} />
According to official React docs
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
To avoid the potential security vulnerabilities (such as XSS attacks) that are present when using dangerouslySetInnerHTML, you can do the following:
First use DOMPurify to clean the HTML.
import DOMPurify from 'dompurify';
let clean = DOMPurify.sanitize(dirtyHtmlString, {USE_PROFILES: {html: true}});
Then it can be rendered using react-render-html as Salman Lone said:
import renderHTML from 'react-render-html';
<div>
{renderHTML(clean)}
</div>
in my case, I used following pacakge.
react-render-html
According to the website "https://reactjs.org/docs/dom-elements.html" you should use dangerouslySetInnerHTML in order to avoid cross-site scripting (XSS) attacks. However, if you are controlling the string that you want to render then that may not be necessary. If you wish to render HTML this way then as the above website explains, you may do so in this way:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
I personally do not like the dangerouslySetInnerHTML method (mostly because it has the word dangerous and that scares me). I cannot say if the next method is better, safer, faster etc but I like it much more. The second method that you can use is to render the HTML with useRef.
An example of this method is:
import React, {useRef, useEffect} from 'react'
export default function Example() {
const aRef = useRef()
const content = '<p style="color:red">hello</p><h1>world</h1>'
useEffect(()=>{
if(aRef==null)return
aRef.current.innerHTML = content
},[aRef, content])
return <div ref={aRef}/>
}
I forgot to do testing for setting class, id, ref, values etc via string.
If someone wants to add to this answer, please add examples for every React operation like I have done with style.

How do I convert a string to jsx?

How would I take a string, and convert it to jsx? For example, if I bring in a string from a textarea, how could I convert it to a React element;
var jsxString = document.getElementById('textarea').value;
What is the process I would use to convert this on the client? Is it possible?
You can consider using the React attribute dangerouslySetInnerHTML:
class YourComponent{
render() {
someHtml = '<div><strong>blablabla<strong><p>another blbla</p/></div>'
return (
<div className="Container" dangerouslySetInnerHTML={{__html: someHtml}}></div>
)
}
}
Personally, I love to do it just like in the previous answer which recommends the usage of dangerouslySetInnerHTML property in JSX.
Just for an alternative, nowadays there is a library called react-html-parser. You can check it and install from NPM registry at this URL: https://www.npmjs.com/package/react-html-parser. Today's weekly download statistic for that package is 23,696. Looks a quite popular library to use. Even it looks more convenient to use, my self, still need more read and further consideration before really using it.
Code snippet copied from the NPM page:
import React from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
class HtmlComponent extends React.Component {
render() {
const html = '<div>Example HTML string</div>';
return <div>{ ReactHtmlParser(html) }</div>;
}
}
Here's how you can do it, without using dangerouslySetInnerHTML.
import React from "react";
let getNodes = str =>
new DOMParser().parseFromString(str, "text/html").body.childNodes;
let createJSX = nodeArray => {
return nodeArray.map(node => {
let attributeObj = {};
const {
attributes,
localName,
childNodes,
nodeValue
} = node;
if (attributes) {
Array.from(attributes).forEach(attribute => {
if (attribute.name === "style") {
let styleAttributes = attribute.nodeValue.split(";");
let styleObj = {};
styleAttributes.forEach(attribute => {
let [key, value] = attribute.split(":");
styleObj[key] = value;
});
attributeObj[attribute.name] = styleObj;
} else {
attributeObj[attribute.name] = attribute.nodeValue;
}
});
}
return localName ?
React.createElement(
localName,
attributeObj,
childNodes && Array.isArray(Array.from(childNodes)) ?
createJSX(Array.from(childNodes)) :
[]
) :
nodeValue;
});
};
export const StringToJSX = props => {
return createJSX(Array.from(getNodes(props.domString)));
};
Import StringToJSX and pass the string in as props in the following format.
<StringToJSX domString={domString}/>
PS: I might have missed out on a few edge cases like attributes.
I came across this answer recently and, it was a good deal for me. You don't need to provide a string. Returning an array of JSX elements will do the trick.
We can store JSX elements in JavaScript array.
let arrUsers = [<li>Steve</li>,<li>Bob</li>,<li>Michael</li>];
and in your HTML (JSX) bind it like,
<ul>{arrUsers}</ul>
As simple as it is.
If you consider string
<div>Hello World</div>
If we are very strict, this actually is the valid JSX. The question is how to compile this JSX string into React code.
Easiest and the recommended way is to download some library like Babel and use it to transform the code. Babel can run in the Browser like the repl does.
It is also possible to transform JSX to other formats, but in this case you have to find a compiler or create one yourself.
The steps to create the JSX => React transformation yourself is:
transform the code string into AST representation
parse the AST and output code back to string
So you need somekind of AST parser like espree supporting JSX and then you can create a code which walks the AST tree and outputs something, like React -code out of it.
The AST tree of JSX data consists of normal JavaScript AST together with JSX nodes. The parser should walk through the tree and transform the JSX nodes into normal JavaScript code.
If you compile to React and encounter a JSX node with tag "div" you should compile that into React.createElement("div",... call with attributes and subnodes found under that AST node inserted as parameters of that call.
I have created a small AST Walker, which can process AST tree, ASTWalker, which can be used to transform the AST tree into some output format, like React or DOM.
On-line example of how to use it is here:
http://codepen.io/teroktolonen/pen/KzWVqx?editors=1010
The main code looks like this:
// here is the JSX string to parse
var codeStr = "<div>Hello world</div>";
var walker = ASTWalker({
defaultNamespace: "react",
});
// compile AST representation out of it.
var rawAST = espree.parse(codeStr, {
ecmaVersion: 6,
sourceType: "script",
// specify additional language features
ecmaFeatures: {
// enable JSX parsing
jsx: true
}
});
// then you can walk the walk to create the code
walker.startWalk( rawAST, {} );
var code = walker.getCode();
console.log(code);
document.getElementById("sourceCode").innerHTML = code;
DISCLAIMER: The library is not intented for compiling into React. It is mostly used with defaultNamespace: "DOM", using it to compile into plain JavaScript + DOM representation. Trying anything more complicated than simple tags may result as an error.
The important thing is to notice that React is not only possible output format for JSX.
I've been using html-to-react with some success (self closing tags cause a problem though, but a fix is in the pull requests...) to parse markup strings as DOM like objects, and in turn React elements. It's not pretty, and if you can avoid it, do so. But it gets the job done.
html-to-react at github: https://github.com/mikenikles/html-to-react
Use React-JSX-Parser
You can use the React-JSX-Parser library dedicated for this.
npm install react-jsx-parser
here is the repo
html-react-parser is what you need.
import parse from 'html-react-parser';
import React from 'react';
export default function YourComponent() {
someHtml = '<div><strong>blablabla<strong><p>another blbla</p/></div>'
return (
<div className="Container">{parse(someHtml)}</div>
)
}
Here's a little utility component for this:
const RawHtml = ({ children="", tag: Tag = 'div', ...props }) =>
<Tag { ...props } dangerouslySetInnerHTML={{ __html: children }}/>;
Sample usage:
<RawHtml tag={'span'} style={{'font-weight':'bold'}}>
{"Lorem<br/>ipsum"}
</RawHtml>
First you can change it to a non-string array and then use it as JSX
class ObjReplicate extends React.Component {
constructor(props) {
super(props);
this.state = { myText: '' };
}
textChange=(e) =>{this.setState({ myText: e.target.value })};
render() {
const toShow = this.state.myText;
var i=1;
var allObjs=new Array;
while (i<100){
i++;
allObjs[i] = <p>{toShow}</p>; //non-sting array to use in JSX
}
return (
<div>
<input onChange={this.textChange}></input>
{allObjs}
</div>
);
}
}
ReactDOM.render(<ObjReplicate/>,document.getElementById('root'));
You need to use babel with preset react
npm install --save-dev babel-cli babel-preset-react
Add the following line to your .babelrc file:
{
"presets": ["react"]
}
Then run
./node_modules/.bin/babel script.js --out-file script-compiled.js
You can find more info here

Output object name other than React with jsx syntax

with React v0.12 the #jsx pragma is gone which means it is no longer possible to output jsx with anything other than the React.METHODNAME syntax.
For my use case I am trying to wrap the React object in another object to provide some convenience methods thus, in my component files, I want to be able to write:
var myConvenienceObject = require('React-Wrapper');
var Component = myConvenienceObject.createSpecializedClass({
render: function () {
return <div />
}
})
However the jsx compiler automatially converts <div /> into React.createElement("div", null)
With older versions of React it was possible to handle this using the pragma at the top of the file. However, since that has been removed, I was wondering if there was any way currently to change the name of the object compiled by jsx so <div /> would be transformed into myConvenienceObject.createElement("div", null)
No, it's no longer possible to use a custom prefix for JSX. If you need to do this, you'll need to modify the JSX transform code, or create a fake React.
var React = require('react'), FakeReact = Object.assign({}, React, {
createElement: function(component, props, ...children){
// ...
// eventually call the real one
return React.createElement(component, props, ...children);
}
});
module.exports = FakeReact;
And then to use it you import the fake react and call it React.
var React = require('fake-react');
// ...
render: function(){ return <div />; }
If you would like to make some elements contains in your myConvenienceObject, you could consider the children props as shown in the doc. But this may need some changes in the myConvenienceObject too, to accept the children.
By the way, i'm not sure where is this createSpecializedClass functions comes from and what it does

Resources