Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set innerHTML jsx format

So I given this code:

render() {
  console.log(this.props, 'ey');
  const var1 = "<div className={{blahblah}} style={{width: '10px'}}>{textvar}</div>"


  return (
    <div dangerouslySetInnerHTML={{ __html: `${var1}` }}>
    </div>
  );
}

Of course that's just an example, but the var1 should be a big chunk of html file in jsx format, however doing that one renders them as they are and doesn't convert them to regular html.

I also tried setting innerHTML via refs on componentDidMount but same problem happens.

this is what it should look like when it renders:

<div class="blahblah style="width: 10px"}}>the variable text</div>

Any help would greatly appreciated. thanks!

like image 943
I am L Avatar asked Apr 26 '17 00:04

I am L


People also ask

How should you set innerHTML in React?

dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.

Can we use innerHTML in React?

innerHTML prop is risky because it is easy to expose your users to a cross-site scripting (XSS) attack. React provides dangerouslySetInnerHTML as a replacement for innerHTML prop to remind yourself that it is dangerous. Therefore, you should use dangerouslySetInnerHTML prop instead of innerHTML prop.

Can you write JavaScript in JSX?

Coding JSXJSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.

What is JSX syntax?

JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code). It is easy to create a template using JSX in React, but it is not a simple template language instead it comes with the full power of JavaScript.


1 Answers

You need to do this to use ES6 interpolated string literals (inaccurately called template literals by the spec):

<div dangerouslySetInnerHTML={{ __html: `${var1}` }}>

But this would be simpler:

<div dangerouslySetInnerHTML={{ __html: var1 }}>

However, in your string for the inner html, you may want to use an interpolated string literal if what you want is to use the values of the blahblah and textvar variables. Note you need to use class instead of className since React will just set the inner html rather than treat it as JSX and className is only for JSX.

const var1 = `<div class=${blahblah}>${textvar}</div>`;

If you are using a class, no need to also use the style keyword. Just set the width in your CSS.

You can see a working example of the above on CodePen.

like image 173
Todd Chaffee Avatar answered Oct 11 '22 07:10

Todd Chaffee