While creating a tic-tac-toe game on React js. whenever I click on a single tile, it re-renders for all other tiles too.
const Game = () => {
const [xIsNext, setXIsNext] = useState(true);
const [stepNumber, setStepNumber] = useState(0);
const [history, setHistory] = useState([{ squares: Array(9).fill(null) }]);
const updatedHistory = history;
const current = updatedHistory[stepNumber];
const winner = CalculateWinner(current.squares);
const move = updatedHistory.map((step, move) => {
const desc = move ? `Go to # ${move}` : "Game Start";
const jumpTo = (step) => {
setStepNumber(step);
setXIsNext(step % 2 === 0);
};
return (
<div key={move}>
<button className="btninfo" onClick={() => jumpTo(move)}>{desc}</button>
</div>
);
});
let status;
if (winner) {
status = `Winner is ${winner}`;
} else {
status = `Turn for Player ${xIsNext ? "X" : "O"}`;
}
const handleClick = (i) => {
const latestHistory = history.slice(0, stepNumber + 1);
const current = latestHistory[latestHistory.length - 1];
const squares = current.squares.slice();
const winner = CalculateWinner(squares);
if (winner || squares[i]) {
return;
}
squares[i] = xIsNext ? "X" : "O";
setHistory(history.concat({ squares: squares }));
setXIsNext(!xIsNext);
setStepNumber(history.length);
};
const handleRestart = () => {
setXIsNext(true);
setStepNumber(0);
setHistory([{ squares: Array(9).fill(null) }]);
};
return (
<div className="game">
<div className="game-board">
<div className="game-status">{status}</div>
<Board onClick={handleClick} square={current.squares} />
</div>
<div className="game-info">
<button className="btninfo" onClick={handleRestart}>Restart</button>
<div>{move}</div>
</div>
</div>
);
};
export default Game;
const CalculateWinner = (squares) => {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[b] === squares[c]) {
return squares[a];
}
}
return null;
};
and the Board component on which Parameter is passed is
const Board = (props) => {
const renderSquare = (i) => {
return <Square value={props.square[i]} onClick={() => props.onClick(i)} />;
};
return (
<div>
<div className="border-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="border-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="border-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
);
};
export default Board;
which leads to the single Square component mentioned below, which re-renders for all tiles if we click a single tile.
const Square = (props) => {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
};
export default Square;
I tried with useCallback on handleClick function, and kept the second parameter as an empty array, then also it didn't work.
How can I prevent the re-rendering of other tiles?
If a React component's parent rerenders, it will cause the child to rerender unless the component is optimized using React.memo or the shouldComponentUpdate life cycle method handles this.
Since yours is a functional component just do this while exporting:
export default React.memo(Square);
As mentioned in the docs, React.memo does a shallow check of props and if found different returns true. This can be controlled using the second argument of the function, which is a custom equality checker.
One of the props for Square is an object (the function - onClick={() => props.onClick(i)}). This is obviously created new everytime. A function object is equal only to itself.
You will have to use useCallback so the function is not created in every cycle.
const handleClick = useCallback((i) => {
const latestHistory = history.slice(0, stepNumber + 1);
const current = latestHistory[latestHistory.length - 1];
const squares = current.squares.slice();
const winner = CalculateWinner(squares);
if (winner || squares[i]) {
return;
},[history,latestHistory,squares]);
````
You might have to do the same here too:
````
const renderSquare = (i) => {
cont clickHandler = useCallback(() => props.onClick(i),[props.onClick]);
return <Square value={props.square[i]} onClick={clickHandler} />;
};
````
Related
I am trying to make a Sudoku solver. I have a parent component Board and a child component Possible which shows available options for any box in the board. I passed the state of board,selected(selected box position in the board) and function to update board as props. But when I try to change board from Possible it doesn't change unless the selected box selected is changed from parent component. I am trying to change board element from child component.
Here is my Board component.
import React, { useState } from 'react';
import Possibles from './avails.jsx';
import solve, { initBoard } from '../help';
function Board() {
const [msg, setmsg] = useState('');
const [solved, setSolved] = useState(false);
const [grid, setGrid] = useState(initBoard());
const [selected, setSelected] = useState([0, 0]);
const solveBoard = () => {
const solution = solve(grid);
setGrid(solution);
setSolved(true);
let a = true;
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
// console.log(i,j)
if (grid[i][j] === 0) {
// console.log(grid[i][j]);
a = false;
}
}
}
if (!a) {
setmsg('Invalid Board!');
} else setmsg('Here is your solution!');
};
const updatePosition = (row, col) => {
setSelected([row, col]);
};
const resetBoard = () => {
setGrid(initBoard());
setSolved(!solved);
setmsg('');
};
return (
<div className="board">
Sudoku Solver
{grid.map((row, index) => (
<div key={index} className="row">
{row.map((el, i) => (
<button
type="button"
key={i}
className={selected[0] === index && selected[1] === i ? 'el selected' : 'el'}
onClick={() => { updatePosition(index, i); }}
>
{el === 0 ? '' : el}
</button>
))}
</div>
))}
{setSolved
? <Possibles board={grid} pos={selected} setGrid={setGrid} setPos = {setSelected}/> : ''}
<button type="button" className="btn" onClick={solveBoard}>Solve</button>
<button type="button" className="btn" onClick={resetBoard}>Reset</button>
<div>{msg}</div>
</div>
);
}
export default Board;
And here is my child component Possibles.
import React, { useState, useEffect } from 'react';
import { getAvailableNumbers } from '../help';
function Possibles({ board, pos, setGrid }) {
const [possibles, setPosibles] = useState([]);
useEffect(() => {
const avails = getAvailableNumbers(board, pos);
avails.unshift(0);
setPosibles(avails, board, possibles);
}, [pos,board]);
const updateGrid = (opt) => {
// setPosibles((prev) => prev.filter((x) => x !== opt || x === 0));
board[pos[0]][pos[1]] = opt;
setGrid(board);
};
return (
<div>
{possibles.map((opt) => (
<button type="button" key={opt} onClick={() => { updateGrid(opt); }}>{opt === 0 ? 'X' : opt}</button>
))}
</div>
);
}
export default Possibles;
please change your 'updateGrid' function to -
const updateGrid = (opt) => {
// setPosibles((prev) => prev.filter((x) => x !== opt || x === 0));
board[pos[0]][pos[1]] = opt;
board = [...board]; // this will make parent component rerender
setGrid(board);
};
input to setPosibles should be an array according to first line of 'Possibles' component -
setPosibles(avails, board, possibles);
Edit - react basically uses shallow comparison for props, state to detect new available change. By using a spread operator we are a creating new array with a new memory location, this let react know about new change and rerendering is triggered.
I have the following code:
import React, { useState } from "react";
export default function App() {
const [arr, setArr] = useState([
{ id: 1, name: "orange" },
{ id: 2, name: "lemon" },
{ id: 3, name: "strawberry" },
{ id: 4, name: "apple" }
]);
const onMoveUp = function (key) {
if (key === 0) return;
const items = arr;
const index = key - 1;
const itemAbove = items[index];
items[key - 1] = items[key];
items[key] = itemAbove;
console.log(items);
setArr(items);
};
const onMoveDown = function (key) {
const items = arr;
if (key === items.length - 1) return;
const index = key + 1;
const itemBelow = items[index];
items[key + 1] = items[key];
items[key] = itemBelow;
setArr(items);
};
return (
<div>
<ul>
{arr.map((item, key) => (
<li key={key}>
<div>
{item.id} - {item.name}
</div>
<div>
<span onClick={() => onMoveUp(key)}>▲</span>
<span onClick={() => onMoveDown(key)}>▼</span>
</div>
</li>
))}
</ul>
</div>
);
}
What it is supposed to do is move list elements up and down using the arrows. I have tried many ways but nothing seems to work. I am currently exploring useEffect. The array does change but it is not reflected in the UI. Please help.
It is not advisable to change the state value directly. It is better to make a copy of your state
Good learning
Here is an example with spread operator :
import React, { useState } from "react";
export default function App() {
const [arr, setArr] = useState([
{ id: 1, name: "orange" },
{ id: 2, name: "lemon" },
{ id: 3, name: "strawberry" },
{ id: 4, name: "apple" }
]);
const onMoveUp = function (key) {
if (key === 0) return;
const items = [...arr];
const index = key - 1;
const itemAbove = items[index];
items[key - 1] = items[key];
items[key] = itemAbove;
console.log(items);
setArr(items);
};
const onMoveDown = function (key) {
const items = [...arr];
if (key === items.length - 1) return;
const index = key + 1;
const itemBelow = items[index];
items[key + 1] = items[key];
items[key] = itemBelow;
setArr(items);
};
return (
<div>
<ul>
{arr.map((item, key) => (
<li key={key}>
<div>
{item.id} - {item.name}
</div>
<div>
<span onClick={() => onMoveUp(key)}>▲</span>
<span onClick={() => onMoveDown(key)}>▼</span>
</div>
</li>
))}
</ul>
</div>
);
}
In React, the UI must be changed to a new object in the state in order to be updated. A framework like React uses immutability for state management.
For example, in your function onMoveUp, items are the same array as arr made with useState. React does not update the UI because you mutate the same object and store this value in the state.
Save the new object in the state by modifying the code as follows:
const onMoveUp = function (key) {
if (key === 0) return;
const items = [...arr]; // Create a new object with Copy Object
const index = key - 1;
const itemAbove = items[index];
items[key - 1] = items[key];
items[key] = itemAbove;
console.log(items);
setArr(items);
};
How to have second state produced from first state and when the first one changes, make second state to react in response to update it ?
It worked but I am not sure how reliable is doing it that way, any suggestions ? Thanks.
export default function App() {
const [arr, setArr] = useState([1, 2, 3, 4, 5]);
const [length, setLength] = useState(arr.length);
console.log(arr)
const clickHandler = () => {
setArr([...arr, arr.length+1])
};
useEffect(() => {
setLength(length + 1)
}, [arr])
return (
<div className="App">
<h2>{length}</h2>
<button onClick={clickHandler}>click</button>
</div>
);
}
so you want the 'second state' (length) to be updated every time the length of the array changes. For that, you need an effect that will take the length of the array as a dependency (arr.length), and then set length to that value.
Also added a change to the clickHandler function as the state is computed from the previous state (check this for further details)
This is how the final code would look
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [arr, setArr] = useState([1, 2, 3, 4, 5]);
const [length, setLength] = useState(arr.length);
console.log(arr);
const clickHandler = () => {
setArr((arr) => [...arr, arr.length + 1]); // Change #1
};
useEffect(() => {
setLength(arr.length); // Change #2
}, [arr.length]);
return (
<div className="App">
<h2>{length}</h2>
<button onClick={clickHandler}>click</button>
</div>
);
}
I'm trying React.js and I followed a tutorial to make a morpion game. Now, I'm trying to get the choice of the user, where he clicked, and print the column and line. Here's what I've done so far:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<button
className="square"
onClick={props.onClick}
>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return <Square
value={this.props.squares[i]}
onClick={ () => this.props.onClick(i)}
/>;
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
choice: null,
}],
stepNumber: 0,
xIsNext: true,
};
}
jumpTo(step){
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
//Si quelqu'un a gagné, on empêche le clic
if (calculateWinner(squares) || squares[i]){
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const choice = (current) => { this.calculateChoice(current.squares) };
const moves = history.map((step, move) => {
const desc = move ?
'Revenir au tour n°' + move :
'Revenir au début de la partie';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
let status;
if (winner){
status = winner + ' a gagné';
} else {
status = 'Prochain joueur : ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={ (i) => {
this.handleClick(i);
} }
/>
</div>
<div className="game-info">
<div>Coup {choice}</div>
<div>{ status }</div>
<ol>{ moves }</ol>
</div>
</div>
);
}
}
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++){
const [a, b, c] = lines[i];
if(squares[a] && squares[a] === squares[b] && squares[a] === squares[c]){
return squares[a];
}
}
return null;
}
function calculateChoice(squares){
const lines = [
[0,0],[0,1],[0,2],
[1,0],[1,1],[1,2],
[2,0],[2,1],[2,2],
];
for (let i = 0; i < lines.length; i++){
const [a, b] = lines[i];
return "test ".squares[a];
}
return "test";
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
I defined a const choice, where I want to put the choice of the user. Then I call calculateChoice, but nothing is displayed when I try { choice }. I don't know why. Also, I don't know how to get the line and column of where the user clicked. I made a tab of the different choices but then I don't know how to compare them to the Square the user clicked.
Thanks
Edit:
So I changed the const choice:
const choice = calculateChoice(current.squares);
Now it works, I get a display. But I don't know how to get the column and line of where the user clicked. I started with the calculateChoice but I don't know where I'm going with this.
What I would like is:
The user click on a Square. The 'X' or 'O' is affected to the Square and then it displays "choice" which corresponds to (line,column) of where the user clicked. Thanks for any explanation to how to develop that!
This is a function, const choice = (current) => { this.calculateChoice(current.squares) };
If you render <div>Coup {choice}</div>, of course it won't render any value, because it's a function.
This function won't return proper value because it's not meant to return anything. You can either do const choice = (current) => { return this.calculateChoice(current.squares) }; or const choice = (current) => this.calculateChoice(current.squares);
If you want to call this.calculateChoice(current.squares), make sure it's inside the class component.
I'm practicing with the new hooks functionnality in ReactJS by refactoring the code from this tutorial with TypeScript.
I am passing a callback from a parent component to a child component threw props that has to be executed on a click button event.
My problem is this: I have an alert dialog that appears twice instead of once when the game has been won.
I assumed this was caused by a component re-rendering so I used the useCallback hook to memoize the handleClickOnSquare callback. The thing is, the alert dialog still appears twice.
I guess I'm missing something that has a relation with re-rendering, does someone have an idea what might cause this behavior ?
Here is my code:
Game.tsx
import React, { useState, useCallback } from 'react';
import './Game.css';
interface SquareProps {
onClickOnSquare: HandleClickOnSquare
value: string;
index: number;
}
const Square: React.FC<SquareProps> = (props) => {
return (
<button
className="square"
onClick={() => props.onClickOnSquare(props.index)}
>
{props.value}
</button>
);
};
interface BoardProps {
squares: Array<string>;
onClickOnSquare: HandleClickOnSquare
}
const Board: React.FC<BoardProps> = (props) => {
function renderSquare(i: number) {
return (
<Square
value={props.squares[i]}
onClickOnSquare={props.onClickOnSquare}
index={i}
/>);
}
return (
<div>
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
);
};
export const Game: React.FC = () => {
const [history, setHistory] = useState<GameHistory>(
[
{
squares: Array(9).fill(null),
}
]
);
const [stepNumber, setStepNumber] = useState(0);
const [xIsNext, setXIsNext] = useState(true);
const handleClickOnSquare = useCallback((index: number) => {
const tmpHistory = history.slice(0, stepNumber + 1);
const current = tmpHistory[tmpHistory.length - 1];
const squares = current.squares.slice();
// Ignore click if has won or square is already filled
if (calculateWinner(squares) || squares[index]) return;
squares[index] = xIsNext ? 'X' : 'O';
setHistory(tmpHistory.concat(
[{
squares: squares,
}]
));
setStepNumber(tmpHistory.length);
setXIsNext(!xIsNext);
}, [history, stepNumber, xIsNext]);
const jumpTo = useCallback((step: number) => {
setHistory(
history.slice(0, step + 1)
);
setStepNumber(step);
setXIsNext((step % 2) === 0);
}, [history]);
const current = history[stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const desc = move ?
'Go back to move n°' + move :
'Go back to the start of the party';
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{desc}</button>
</li>
);
});
let status: string;
if (winner) {
status = winner + ' won !';
alert(status);
} else {
status = 'Next player: ' + (xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClickOnSquare={handleClickOnSquare}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
function calculateWinner(squares: Array<string>): string | null {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
types.d.ts
type GameHistory = Array<{
squares: Array<string>
}>;
type HandleClickOnSquare = (index: number) => void;
Thanks
Your code is too long to find the cause of extra rerender. Note that React might need an extra render.
To avoid an extra alert use useEffect:
let status: string;
if (winner) {
status = winner + ' won !';
} else {
status = 'Next player: ' + (xIsNext ? 'X' : 'O');
}
useEffect(() => {
if (winner) alert(status)
}, [winner]);