'Page reloads when I use the setState function in React.js
When I use setState to change the object, the page reloads, resetting everything on the page. As I am making a tic-tac-toe app, either an X or 0 appears when I click on divs but when I use setState to change anything, the webpage resets, taking back everything to its initial position.
<script type="text/babel">
function TicTacToe() {
const [state, setState] = React.useState({
turn: 0,
player: 'player1'
});
function changePlayer() {
if (state.player === 'player2') {
setState({
... state,
player: 'player1'
})
} else if (state.player === 'player1') {
setState({
... state,
player: 'player2'
})
}
}
function playerTurn() {
if (state.turn % 2 === 0) {
setState({
... state,
player: 'player1'
})
} else {
setState({
... state,
player: 'player2'
})
}
}
function columnClicked(event) {
let element = event.target;
if (state.player === 'player2') {
element.innerHTML= '<h1 class="symbols">0</h1>';
} else if (state.player === 'player1') {
element.innerHTML= '<h1 class="symbols">X</h1>';
}
}
return (
<div>
<Heading />
<div className='container'>
<CreateRow />
<CreateRow />
<CreateRow />
</div>
<button onClick={ changePlayer }>Change Player</button>
</div>
);
}
ReactDOM.render(<TicTacToe />, document.getElementById('tic_tac_toe'));
</script>
Solution 1:[1]
Prevent a browser reload/refresh by using event.preventDefault()
as follows.
function changePlayer(event) {
event.preventDefault()
if (state.player === 'player2') {
setState({
... state,
player: 'player1'
})
} else if (state.player === 'player1') {
setState({
... state,
player: 'player2'
})
}
}
Solution 2:[2]
There are two different things and two different approaches:
If you want to stop unnecessary re-render:
shouldComponentUpdate() {
return false; // This will cause component to never re-render.
}
If you want to stop unnecessary refresh on setState
:
demoFunction(event) {
event.preventDefault();
this.setState({sample: true});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kavindu Vindika |
Solution 2 | Rahul |