Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 556
jhamm Avatar asked Oct 18 '22 14:10

jhamm


People also ask

How convert string from HTML to JSX in React?

There're several ways to convert HTML Strings to JSX with React. One way is to put the string in between curly braces in our component. Another way is to put the string in an array with other strings or JSX code. Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.

Is JSX a string?

This funny tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

Can you write JavaScript in JSX?

JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together. This is simple JSX code in React.

Is JavaScript and JSX same?

Conclusion. JS is simply a scripting language, adding functionality into your website. JSX is an addition to the JavaScript syntax which is a mixture of both HTML and JavaScript. Both JS and JSX are interchangeable but JSX makes the code easier to understand for users.


2 Answers

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>
    )
  }
}
like image 170
user8296051 Avatar answered Oct 25 '22 16:10

user8296051


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>;
  }
}
like image 31
Bayu Avatar answered Oct 25 '22 17:10

Bayu