I am trying to make a calculator, but when i click the number buttons, the screen doesnt update. I checked the handler, and it seems like it should work. I also logged the calc(see code for reference) and it is not updating. What is wrong?
import React, {useState} from 'react';
import Screen from './screen.js'
import Button from './button.js'
import ButtonBox from './buttonBox.js'
const btnValues = [
["C", "+-", "%", "/"],
[7, 8, 9, "X"],
[4, 5, 6, "-"],
[1, 2, 3, "+"],
[0, ".", "="],
];
const CalcBody =() => {
{/*res as in result */}
let [calc, setCalc] = useState({
sign: "",
num: 0,
res: 0,
});
const numClickHandler = (e) => {
e.preventDefault();
const value = e.target.innerHTML;
if (calc.num.length < 16) {
setCalc({
...calc,
num:
calc.num === 0 && value === "0"
? "0"
: calc.num % 1 === 0
? Number(calc.num + value)
: calc.num + value,
res: !calc.sign ? 0 : calc.res,
});
}
console.log(calc.num)
};
return (
<div className="wrapper">
<Screen value={calc.num ? calc.num : calc.res} />
<ButtonBox>
{btnValues.flat().map((btn, i) => {
return (
<Button
key={i}
className={btn === "=" ? "equals" : ""}
value={btn}
onClick={numClickHandler
}
/>
);
})}
</ButtonBox>
</div>
);
}
export default CalcBody;
Related
import React, { useState } from 'react';
const Calculator = () => {
const [displayValue, setDisplayValue] = useState('0');
const [operations, setOperations] = useState([]);
const handleClick = (e) => {
const value = e.target.getAttribute('data-value');
if (value === 'C') {
setDisplayValue('0');
setOperations([]);
} else if (value === 'CE') {
setDisplayValue('0');
setOperations(operations.slice(0, -1));
} else if (value === '=') {
const result = eval(operations.join(''));
setDisplayValue(result);
setOperations([]);
} else if (!isNaN(value)) {
// Handle number buttons
setDisplayValue(displayValue === '0' ? value : displayValue + value);
} else {
// Handle operation buttons
if (displayValue !== '') {
setOperations([...operations, displayValue, value]);
setDisplayValue('');
}
}
};
const renderButtons = () => {
const buttons = [
['7', '8', '9', '+'],
['4', '5', '6', '-'],
['1', '2', '3', '/'],
['.', '0', 'C', '=']
];
return buttons.map((row) => {
return (
<div className="button-row">
{row.map((button) => {
return (
<button
key={button}
data-value={button}
onClick={handleClick}
>
{button}
</button>
);
})}
</div>
);
});
};
return (
<div className="calculator">
<div className="display">{displayValue}</div>
{renderButtons()}
</div>
);
};
export default Calculator;
This is my code for a simple calculator using react.js
The problem is when I digit a number, for exemple "40", the display only shows 4, and than 0, never 4 and 0 together, although the final result after= is correct.
40+50=90.
But when I digit it only shows 4, than 0, than 5, than 0. One at the time.
How to fix it?
I tried several ways to fix it without good results.
You were not adding the last number that was displaying before clicking the = sign. I've added some conditions to add the last display value
import React, { useState } from "react";
const Calculator = () => {
const [displayValue, setDisplayValue] = useState("0");
const [operations, setOperations] = useState([]);
const handleClick = (e) => {
e.preventDefault();
const value = e.target.getAttribute("data-value");
if (value === "C") {
setDisplayValue("0");
setOperations([]);
} else if (value === "=") {
console.log(operations);
if (operations.length === 0) {
setDisplayValue("0");
} else {
const result = eval(operations.join("") + displayValue);
setDisplayValue(result);
setOperations([]);
}
} else if (!isNaN(value)) {
// Handle number buttons
console.log("num", value);
setDisplayValue(displayValue === "0" ? value : displayValue + value);
} else {
// Handle operation buttons
if (displayValue !== "") {
setOperations([...operations, displayValue, value]);
setDisplayValue("");
}
}
};
console.log("num", displayValue);
console.log("op array", operations);
const renderButtons = () => {
const buttons = [
["7", "8", "9", "+"],
["4", "5", "6", "-"],
["1", "2", "3", "/"],
[".", "0", "C", "="]
];
return buttons.map((row) => {
return (
<div className="button-row">
{row.map((button, index) => {
return (
<button key={index} data-value={button} onClick={handleClick}>
{button}
</button>
);
})}
</div>
);
});
};
return (
<div className="calculator">
<div className="display">{displayValue}</div>
{renderButtons()}
</div>
);
};
export default Calculator;
also I've removed the CE operation as it was serving no purpose
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} />;
};
````
Don't know what I am doing wrong here, maybe it is a rookie mistake.
I am trying to recreate chess.
My state is delayed by one.. i.e. when I click on square to show possible moves of piece, the possible moves will appear but only after my second click, they will show on the right spot. And for the 3rd click the state from 2nd click will appear on the right spot and so on.
What am I doing wrong here?
I am sending few code examples from my next.js app.
This is my Square component
export default function Square({
x,
y,
color,
content,
contentClr,
handleClick,
}) {
const col = color == 'light' ? '#F3D9DC' : '#744253';
return (
<div
className='square'
x={x}
y={y}
style={{ backgroundColor: col }}
onClick={() => handleClick(x, y)}
>
{content != '' && (
<h1 style={{ color: contentClr == 'light' ? 'white' : 'black' }}>
{content}
</h1>
)}
</div>
);
}
This is my Board component
import { useState, useEffect } from 'react';
import Square from './square';
import styles from '../styles/Board.module.css';
import rookMoves from './possibleMoves/rookMoves';
export default function Board({ initialBoard, lightTurn, toggleTurn }) {
let size = 8;
const [board, setBoard] = useState(initialBoard);
const [possibleMoves, setPossibleMoves] = useState([]);
//possibleMoves .. each possible move is represented as x, y coordinates.
useEffect(() => {
console.log('board state changed');
}, [board]);
useEffect(() => {
console.log('possible moves state changed');
console.log(possibleMoves);
renderPossibleMoves();
}, [possibleMoves]);
const playerClickOnPiece = (x, y) => {
let pos = getPossibleMoves(x, y, rookMoves, [left, right, up, down]);
setPossibleMoves(pos);
};
//where to is object that has functions for directions in it
const getPossibleMoves = (x, y, movePiece, whereTo) => {
let posMoves = [];
for (let i = 0; i < whereTo.length; i++) {
posMoves = posMoves.concat(movePiece(board, x, y, whereTo[i]));
}
console.log(posMoves);
return posMoves;
};
const renderPossibleMoves = () => {
console.log('board from renderPossibleMoves ', board);
let newBoard = board;
for (let i = 0; i < possibleMoves.length; i++) {
newBoard[possibleMoves[i].y][possibleMoves[i].x] = 10;
}
setBoard(newBoard);
};
const squareColor = (x, y) => {
return (x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1)
? 'light'
: 'dark';
};
const handleClick = (x, y) => {
if (lightTurn && board[y][x] > 0) {
console.log(
`show me possible moves of light ${board[y][x]} on ${x} ${y}`
);
playerClickOnPiece(x, y);
} else if (!lightTurn && board[y][x] < 0) {
console.log(`show me possible moves of dark ${board[y][x]} on ${x} ${y}`);
playerClickOnPiece(x, y);
} else if (board[y][x] == 'Pm') {
playerMove();
}
};
return (
<>
<div className='board'>
{board.map((row, y) => {
return (
<div className='row' key={y}>
{row.map((square, x) => {
return (
<Square
x={x}
y={y}
key={x}
color={squareColor(x, y)}
content={square}
contentClr={square > 0 ? 'light' : 'dark'}
handleClick={handleClick}
playerMove={toggleTurn}
/>
);
})}
</div>
);
})}
</div>
</>
);
}
import { useState } from 'react';
import Board from './board';
let initialBoard = [
[-4, -3, -2, -5, -6, -2, -3, -4],
[-1, -1, -1, -1, -1, -1, -1, -1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[4, 3, 2, 5, 6, 2, 3, 4],
];
export default function Game() {
const [lightTurn, setLightTurn] = useState(true);
const toggleTurn = () => {
setLightTurn(!lightTurn);
};
return (
<Board
initialBoard={initialBoard}
lightTurn={lightTurn}
toggleTurn={toggleTurn}
/>
);
}
I am sending an example that shows only possible moves with rook but if u click on any light piece.
#juliomalves's comment helped!
I was mutating state directly in renderPossibleMoves. Spread operator solved the issue.
from
let newBoard = board;
to
let newBoard = [...board];
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]);