Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In react 18 how to I use createRoot to render a class component?

I’m trying to convert my app to React 18’s render method.

I have a class component that doesn’t render to root element. How do I get the createRoot element to render the component and where do I put

const root = ReactDOM.createRoot(document.getElementById("myrenderelement")); 
// please notice I'm not rendering to root as I said above   ^^^

This goes outside the class definition, in the state… where ?
If I put it outside the class I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Syntax error: Unexpected token (80:6)

  78 |  
  79 |
> 80 |  root.render() {
     |      ^
  81 |      return (
  82 |          <div className="myclass">
  83 |              <div className="container">

Same for

root = ReactDOM.createRoot(document.getElementById("myrenderelement"));
root.render() {

and to

ReactDOM.createRoot(document.getElementById("myrenderelement")).render() {

I always says "Unexpected token" on that line

If I try to:

class MyClass extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            <my state vars>
            root: ReactDOM.createRoot(document.getElementById("myrenderelement"))
        }
    }
    ....

then

this.state.root.render() { <whatever>

I get unexpected token again on render line :/

How do I render the class component ?

>Solution :

It doesn’t matter to root.render whether your component is a class component or a function component. In either case, you pass the React element to render to it (usually creating the element via JSX), as shown by the page the dev version of React v18 links to if you use the old way:

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
class Example extends React.Component {
    render() {
        return <div>Hi there</div>;
    }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading