ReactJS: React.render is not a function and React.createElement is not a function

前端 未结 3 1309
情话喂你
情话喂你 2020-12-29 05:57

I found a problem in my code when I was trying to use these two functions in my React version 15.2.0, nonetheless, I found a workaround but I would like to know if there\'s

相关标签:
3条回答
  • 2020-12-29 06:13
    import React from "react"
    import ReactDOM from "react-dom"
    ReactDOM.render(<h1>Hello World!</h1>, document.getElementID("root"))
    
    0 讨论(0)
  • 2020-12-29 06:31

    First of all, since React v0.14, there is this new package called react-dom. It abstracts the "environment" that you will run React, and, in your case, is the browser.

    https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#two-packages-react-and-react-dom

    So, since you have now two packages: "react" to create your React components and "react-dom" to "integrate" React with the browser, you need to call the correct methods that each one of them provides.

    Then, answering your questions:

    Why the react-dom created the problem with React.createElement?

    The package that has React.createElement is react and not react-dom.

    Is it because of this new version of React?

    Yes, you are not able to call React.render (from package react) anymore, you need to use ReactDOM.render (from package react-dom).

    Is there a better approach to solve these problems without having to invoke react-dom and react?

    I don't see it as a "problem", you just need to know that now there is a specific package to manipulate DOM. Also, it is a "good" pattern, because if sometime you want to render your components as an HTML (to render it using a server), you just need to adapt some things and your code will be the same.

    0 讨论(0)
  • 2020-12-29 06:34

    I was getting error: "React.createElement is not a function" and for my situation the fix was to change this:

    import * as React from "react";
    import * as ReactDOM from "react-dom";
    

    TO THIS:

    import React from "react";
    import ReactDOM from "react-dom";
    

    This was in a TypeScript file so i'm not sure it applies to non-TypeScript or not.

    0 讨论(0)
提交回复
热议问题