0

i create a tic tac game and create 2 components PlayerOne and PlayerTwo with 2 inpute to get first & second of player name and use react router to create multipages site to brows the 3 components amd give first & second players names to display them in GameArea Component but i can access the playerOneName & playerTwoName variables in the GameArea so how to export and import them in gamearea to use to display there names

the PlayerOne Components name

import React, { useState } from 'react';
import './PlayerOneS.css';
import PlayerTwo from './PlayerTwo';
import {BrowserRouter, Route,Link, Outlet} from 'react-router-dom';


function PlayerOne() {

  const [playerOneFirstName, setPlayerOneFirstName] = useState('');
  const [playerOneLastName, setPlayerOneLastName] = useState('');
  const playerOneName = `${playerOneFirstName}  ${playerOneLastName}`;
  

  return (
    <>
      <div className="container">
        <h1>Welcome to Tic Tac Toe Game</h1>
        <h2 className='player-name'>Player Name is : {playerOneName} </h2>
        <div className='form' >
          <form>
            <h2><label>Add First Player:</label></h2>
            <div className='inputs'>
              <div className='field'> 
                <label>First Name</label>
                <input onChange={(e) => setPlayerOneFirstName(e.target.value)} type="text" name="playerOneFirstName" placeholder="First Name" />
              </div>
              <div className='field'> 
                <label>Last Name</label>
                <input onChange={(e) => setPlayerOneLastName(e.target.value)} type="text" name="playerOneLastName" placeholder="Last Name" />
              </div>
            </div>
            <button><Link className='link' to='/playertwo'>Continue</Link></button>
          </form>
        </div>
      </div> 
    </>
  )
}

export default PlayerOne

the GameArea Components

import React, { useState } from 'react';
import './GameAreaStyle.css';
import PlayerOne from '../SelectPlayers/PlayerOne';
import {playerOneName} from '../SelectPlayers/PlayerOne';

const GameArea = () => {
    const [playerName, setPlayerName] = useState('osama Zinhom');
    const [player1Name, setPlayer1Name] = useState('osama Zinhom');
    const [player2Name, setPlayer2Name] = useState('Ahmed Zinhom');
    const [turn, setTurn] = useState('x');
    const [cells, setCells] = useState(Array(9).fill(''));
    const [winner, setWinner] = useState();
    
    
    const checkForWinner = (squares) => {
        let combos = {
            across: [
                [0, 1, 2],
                [3, 4, 5],
                [6, 7, 8],
            ],
            down: [
                [0, 3, 6],
                [1, 4, 7],
                [2, 5, 8],
            ],
            diagnol: [
                [0, 4, 8],
                [2, 4, 6],
            ],
        };

        for (let combo in combos) {
            combos[combo].forEach((pattern) => {
                if (
                    squares[pattern[0]] === '' ||
                    squares[pattern[1]] === '' ||
                    squares[pattern[2]] === ''
                ) {
                    // do nothing
                } else if (
                    squares[pattern[0]] === squares[pattern[1]] &&
                    squares[pattern[1]] === squares[pattern[2]]
                ) {
                    setWinner(squares[pattern[0]]);
                }
            });
        }
    };

    const handleClick = (num) => {
        if (cells[num] !== '') {
            alert('already clicked');
            return;
        }

        let squares = [...cells];

        if (turn === 'x') {
            squares[num] = 'x';
            setTurn('o');
        } else {
            squares[num] = 'o';
            setTurn('x');
        }

        checkForWinner(squares);
        setCells(squares);
    };

    const handleRestart = () => {
        setWinner(null);
        setCells(Array(9).fill(''));
    };

    const Cell = ({ num }) => {
        return <td onClick={() => handleClick(num)}>{cells[num]}</td>;
    };

    return (
        <div className='container'>
            <div className='players-container'>
                <h1>Welcome to tic tac Toe Game</h1>
                
                <div className='players-detials'>
                    <h3>Player 1 Name : {playerOneName}</h3>
                    <p>Player Now: {turn}</p>
                    <h3>Player 2 Name : {playerTwoName}</h3>
                </div>
            </div>
            
            {winner && (
                <>
                    <h2>{winner}</h2>
                    <p>Player Name is {playerName}</p>
                </>
            )}

            <table>
                
                <tbody>
                    <tr>
                        <Cell num={0} />
                        <Cell num={1} />
                        <Cell num={2} />
                    </tr>
                    <tr>
                        <Cell num={3} />
                        <Cell num={4} />
                        <Cell num={5} />
                    </tr>
                    <tr>
                        <Cell num={6} />
                        <Cell num={7} />
                        <Cell num={8} />
                    </tr>
                </tbody>
            </table>
            <button onClick={() => handleRestart()}>Reset the Game</button>
            {winner && (
                <>
                    <button onClick={() => handleRestart()}>Start the Game</button>
                </>
            )}
            
        </div>
    );
};

export default GameArea;

The App Components

import './App.css';
import About from './components/About/About';
import Layout from './components/Layout/Layout';
import GameArea from './components/GameArea/GameArea';
import PlayerOne from './components/SelectPlayers/PlayerOne';
import PlayerTwo from './components/SelectPlayers/PlayerTwo';
import { BrowserRouter, Route, Routes } from 'react-router-dom'


function App() {
    return (
        <div className='App'>
            <BrowserRouter>
            <Routes>
                <Route path="/" element={<Layout />}>
                    <Route path="playerone" index  element={<PlayerOne />} />
                    <Route path="playertwo" element={<PlayerTwo />} />
                    <Route path="gamearea" element={<GameArea />} />
                    <Route path="about" element={<About />} />
                </Route>
            </Routes>
            </BrowserRouter>
        </div>
    );
}

export default App;
3
  • Set up states in App component and pass down both state/setters to each child component, or use context api. Either way you can read/update playerOneName & playerTwoName variables. Commented Jul 26, 2022 at 15:26
  • Can you type the code? Commented Jul 26, 2022 at 15:31
  • Please update the question and show us the App component. Commented Jul 26, 2022 at 15:33

1 Answer 1

1

If a state needs to be read or written by multiple components, it must be set in the closest common ancestor of these components.

Then pass the props down to the components using that state.

If you found yourself passing props many layers down, consider using a context.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.