1

I made a dummy React component that does nothing but prints out its this value.

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

class MyComponent extends React.Component {
    constructor() {
        super()
    }

    componentDidMount() {
        console.log(this)
    }

    render() {
        return <div />
    }
}

const myComponent = new MyComponent()
console.log(myComponent)

ReactDOM.render(<MyComponent />, document.getElementById('app'))

I expected that console.log(myComponent) would produce the same result as console.log(this). However, the latter has additional properties (e.g. _reactInternalFiber) and some properties are different (e.g. context, props).

console.log

My question is, how is React or ReactDOM able to provide these additional attributes? You would think that all instances of MyComponent would have the same attributes since they have the same constructor() function, but that is not the case here.

François Maturel
  • 5,884
  • 6
  • 45
  • 50
Narin Luangrath
  • 161
  • 1
  • 8
  • I'm dunno if I'm right but I think. The additional value from the myComponent is due to the scope. The difference I saw was the console.log(this) has the scope only for the component. Unlike for the myComponent where parts of info about the parent component (in which the myComponent was rendered) can be get. _reactInternalFiber is added to the child component whenever it is rendered inside a parent. See this beautiful example https://codesandbox.io/s/l5l18v19m9 from this answer in different question https://stackoverflow.com/questions/50668846 – keysl Aug 08 '18 at 04:17
  • Also note that you have an undefined props and context since you did not pass it on the constructor of your Component. Either way _reactInternal is the only difference between the two – keysl Aug 08 '18 at 04:20
  • 1
    You might need to read more about React component lifecycle and concept of 'mounting' https://stackoverflow.com/questions/31556450/what-is-mounting-in-react-js – blaz Aug 08 '18 at 06:55

0 Answers0