phillip-from-oz
phillip-from-oz

Reputation: 362

Reactjs instantiate a class

I have a question about Reactjs classes.

It appears that Reactjs classes do not need to be instantiated.

import React from 'react'
import ReactDOM from 'react-dom'

class Hello extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>
    }
}

ReactDOM.render(<Hello name="John" />, document.getElementById('root'))
The class Hello is never instantiated but the code works.

However in javascript (ES6) classes can be initiated
class Dog {
  constructor(name) {
    this.name = name;
    this.bark = 'Bow wow';
  }
sayName(){
    return this.name;
  }
bark(){
    return this.bark;
  }
}

// Instance of Dog class
const taro= new Dog('taro')

Why do Reactjs classes not need instantiate when creating an object as in javascript?
Is not Reactjs a superset of javascript?
Is it the compiler that does the instantiation?

Upvotes: 0

Views: 1519

Answers (1)

Snow
Snow

Reputation: 4097

Why do Reactjs classes not need instantiate when creating an object as in javascript?

They do get instantiated. You just don't see where they're done since it's abstracted behind JSX and React's APIs.

Is it the compiler that does the instantiation?

No, it'd done inside React at runtime, inside React.createElement to be precise. It eventually calls constructClassInstance which can be seen here: https://unpkg.com/[email protected]/umd/react-dom.development.js

Upvotes: 1

Related Questions