A react class component is mounted to html root node. It has two react element h1 tag in its body. One h1 element is directly render inside the render method. Another h1 is decleared in React component class and passed into Render function as a variable.
import React, { Component } from "react";
export default class Test extends Component {
state = {
count: 0,
};
current_count = (<h1>current count is {this.state.count}</h1>);
render() {
return (
<>
{this.current_count}
<h1>current count is {this.state.count}</h1>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
click me
</button>
</>
);
}
}
When I clicked the button, it should increase the count, only the react element h1 inside the render function will updated with it's state content.
The following photo is shown the second h1 tag showing count is 4 when I clicked the button 4 times.
Your current_count is a property that gets created in the constructor, before mount, and only then. Your current code is like
export default class Test extends Component {
constructor() {
this.state = {
count: 0,
};
this.current_count = (<h1>current count is {this.state.count}</h1>);
}
And the constructor only runs once.
You'll need some other method to update it. The best way would be to only generate the JSX on render - perhaps have a function instead that returns the <h1>.
class Test extends React.Component {
state = {
count: 0,
};
getCurrentCount() {
return (
<h1>current count is {this.state.count}</h1>
);
}
render() {
return (
<React.Fragment>
{this.getCurrentCount()}
<h1>current count is {this.state.count}</h1>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
click me
</button>
</React.Fragment>
);
}
}
ReactDOM.createRoot(document.querySelector('.react')).render(<Test />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>