EN
React - class component force re-render
0 points
In this article, we would like to show you how to force re-render in a class component in React.
Any change of state causes component rendering, so using e.g. counter
in the state, we are able to force re-rendering always when setState()
method changes (increments) the value of our counter
.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class App extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = { counter: 0 };
9
}
10
11
render() {
12
console.log('App component rednering...');
13
return (
14
<div>
15
<button onClick={() => this.setState({ counter: this.state.counter + 1 })}>
16
force re-rendering
17
</button>
18
</div>
19
);
20
}
21
}
22
23
const root = document.querySelector('#root');
24
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.