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

Time:11-19

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:

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 ?

CodePudding user response:

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>

  • Related