简体   繁体   中英

Is it possible to set a String as html element then use innerhtml on it in react?

import React from "react";

class App extends React.Component {
    render() {

        var formula = "<div> hello </div>"
        
        const div = document.createElement("div")
        div.innerHTML = formula

        return (

            <div>

                {div}

            </div>



        );
    }
}

export default App;

I get an error

Error: Objects are not valid as a React child (found: [object HTMLLIElement]). If you meant to render a collection of children, use an array instead.

Basically the string has html elements I want to set inner html to the div constant. Right now yeah its relatively simple I just need to know if this can be done

My original code has something like this littered throughout my code in recursions too

var formula = "<div>"
formula = formula + "something"
formula = formula + "</div>

You don't need to create a element you can directly use:

   class App extends React.Component {
       render() {

           const formula =<div> hello </div>
           
          
           return (

               <div>

                   {formula}

               </div>



           );
       }
   }

   export default App; 

This cannot be done this way in React. A component can only return a ReactElement or JSXElement. If for some reason you absolutely need to set HTML from a string (there are reasons for this), you have to use dangerouslySetInnerHTML which was made for that precise purpose, but exposes potential security vulnerabilities as explained in the documentation.

You can accomplish this as detailed in the official example:

import React from "react";

class App extends React.Component {
 
    createMarkup() {
       return {__html: 'Hello'};
    }

    render() {

        return (

            <div dangerouslySetInnerHTML={createMarkup()}/>

        );
    }
}

export default App;

But again, this is discouraged and I'm curious to know why you can't just return JSX markup as the other answers suggest.

Why are you creating div like that? I'm begginer in ReactJs,but I think you shouldn't touch / create HTML DOM Elements like that at all or if it is not neccesary.

You can simply just do this.

Let formula = <div> hello </div>

Return(
  <div>
    {formula}
  </div>
)

You can do it with useState.

import {useState} from "react";

const App = () => {

  const [formula, setFormula] = useState("");

  setFormula(<div> 'hello' </div>);


  return(
    <div>
      {formula}
    </div>
  );
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM