I’m confused with render()
and this
in react
, so We got render
method in our
class component
which is the location of our jsx
, so when I use
const root = ReactDOM.createRoot(document.getElementById('root'));
and
root.render(<Counter/>)
in my index.js
file , I expect while Im using <Counter/>
, it retrives the jsx
from render
method but when compile my code, I see it has logged hello
which is located in constructor
section of class component
,so I reached an ambuguity in here , when I use <Counter>
, is react
creating a instance
of my Counter
class component
or it’s just receiving the jsx
from my render
method or even if it’s creating an instance
so why it is logging hello
twice, is that mean it is creating two instances
(and even if it is creating an instance
, the instance creation process is done at <Counter/>
stage, I’ve tested it, no hello
gets logged before <Counter/>
and I’m not sure if it is making 2 instances
or not but it has to call Counter()
twice for logging hello
twice which I guess one of those hello
logs refers to instance
creation which includes Counter()
but I have no idea for second hello
log)
and I got another issue
when I use this
inside render method in my class component
, this
can refer to two objects
:
1.Counter.prototype
,
2.an instance of Counter()
in pure js
, I can determine to refer to which object
but in here because in here I don’t know if there is an instance
or not, I can’t understand what this
refers in render
method, so if anyone can tell whats going on, I’d be glad
by the way if there is an instance
, how react
name it!
code:
//counter.jsx
import React, { Component } from 'react';
class Counter extends Component {
constructor() {
super();
this.name = "jim";
this.age = 46;
console.log("hello");
}
state={
count:9
}
render() {
return (
<>
<h1>{this.state.count}</h1>
<button>increment</button>
</>
);
}
greet(){
console.log("hey");
}
}
export default Counter ;
//index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import "bootstrap/dist/css/bootstrap.css";
import Counter from "./components/counter"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Counter />
);