Participant joins in the game table and reacts

I am looking to set up a table where players can join and have their usernames displayed at the bottom of the screen just like in other games. How can I achieve this?

export const GameStart = (props) => {
  const params = useParams();
  const gameID = params.gameID;
  const { isConnected, client, occupants } = useGameValue();

  const ourTeam = occupants?.findIndex((p) => p.nickname == client.nickname);

  console.log(ourTeam);

  const startGame = () => {
    client.start(gameID);
  };

  const playerIndex = occupants
    .filter((o) => !o.inactive)
    .findIndex((o) => o.nickname === client.nickname);


  const getPlayerStyle = (index) => {
    console.log("condition player index ", playerIndex, index);
    if (index === playerIndex) {
      const rotate = `rotate(0deg) translate(197px)`;
      console.log("if condition", rotate);
      return {
        transform: `${rotate}`,
      };
    } else {
      const angle = 360 / occupants.length;
      const rotate = occupants.length - index;
      const rotation = `rotate(${angle * rotate}deg) translate(197px)`;

      return {
        transform: `${rotation}`,
      };
    }

  };

  
  const playerCount = (players) => {
    return players === 1
      ? "count-1"
      : players === 2
      ? "count-2"
      : players === 3
      ? "count-3"
      : players === 4
      ? "count-4"
      : players === 5
      ? "count-5"
      : players === 6
      ? "count-6"
      : "";
  };

  useEffect(() => {
    if (!client.nickname && isConnected) {
      client.nickname = prompt("enter nickname");
      client.join(gameID, null, client.nickname);
    }
  }, [isConnected]);

  useEffect(() => {
    console.log(occupants, "occupants");
  }, [occupants]);

  return (
    <div className="gameStart">
      <h2>Game</h2>
      {occupants && (
        <div className="table">
          <div
            className={`players ${playerCount(occupants.length)}`}
            style={{ "--rotation-xtra-turns": `${playerIndex}` }}
          >
            {occupants.map((data, index) => {
            return (
                <div
                  className={`player`}
                  style={getPlayerStyle(index)}
                  key={index}
                >
                  {data.nickname}
                </div>
              );
            })}
          </div>
        </div>
      )}
      <button onClick={startGame}>Start Game</button>
    </div>
  );
};

I have tried implementing this solution but it seems to be not working as expected. Specifically, when a new player joins from another device, my previous username remains in the same bottom position on the screen.

I would appreciate it if someone could help me troubleshoot this issue and provide any modifications needed.

Answer №1

My demonstration involves a basic scenario where a function is used to place a player named "jan" at the bottom of the list. You can trigger the sorting function by pressing a button in this case, but feel free to execute it whenever needed. Remember to substitute "jan" with the actual username of the user.

function Example() {
  const [players, setPlayers] = useState(["wim", "henk", "jan", "piet"]);
  
  const sortPlayer = () => {
    const newPlayerList =  [...players].sort((a,b) => {
      return (a === "jan")
    })
    setPlayers(newPlayerList)
  }

  const playerElements = players.map(p => {
        return <div key={p}>{p}</div>
    }
  );
  return (
     <div>
      <button onClick={sortPlayer}>Sort JAN to bottom</button>
      <div>
        {playerElements}
      </div>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

While the NPM package functions properly when used locally, it does not seem to work when installed from the

I have recently developed a command-line node application and uploaded it to npm. When I execute the package locally using: npm run build which essentially runs rm -rf lib && tsc -b and then npm link npx my-package arguments everything works sm ...

Sending the information from a React form to Express using a POST request

Today marks my third day delving into the world of React, and I'm currently working on getting my registration form to successfully post to Express. This will allow me to store the submitted values in my MySQL database for future retrieval. So far, I ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

What is the reason behind the success of this location?

Curious about the functionality of this particular JavaScript code with its corresponding HTML structure: function getCityChoice() { const location = document.querySelector("form").location.value; console.log(location) } <form name="reserve" a ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...

Transmitting data from Javascript/Ajax to a form

I am using jQuery to calculate a price: $('.label_1').click(function(){ var total = 0; $('.option_1:checked').each(function(){ total += parseInt($(this).val()); }); $('#total').html(' ...

Can you explain the distinction between the onclick(function(){}) and on('click',function(){}) functions in jQuery?

My goal is to dynamically load pages into a specific div using ajax. Here's my HTML code: <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink">Tab1</a></li> <li><a href="#" id= ...

How can I avoid duplicating code in HTML? I find myself utilizing the Bootstrap 4 collapse feature around 20 times on a single page

<div class="card" style> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria- expanded="true" aria-controls="collapseO ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Creating distinct short identifiers across various servers

Utilizing the shortid package for creating unique room IDs has proven effective when used on a single server. However, concerns arise regarding the uniqueness of IDs generated when utilized across multiple servers. Is there a method to ensure unique ID g ...

Cost-Effective Method for Refining Search Results of an Item

I am working with a JSON file containing movie data and I'm looking to extract only the top ten highest scoring movies: Here is a snippet of the data: { "movies" : { "eraserhead" : { "full_title" : "Eraserhead", ...

Insert new text and apply class with fadeIn animation

My form is equipped with AJAX functionality. I aim for it to smoothly 'fade in' when the submission is either successful or unsuccessful. In case of success, the script appends the 'has-success' class to the div and alters the content. ...

Encountering an issue in React: Uncaught ReferenceError - require function not recognized

I am currently working on a project that utilizes both react and node (express). When I include react using src="https://unpkg.com/react@16/umd/react.development.js", everything works fine with JSX in the project. However, when I attempt to import like thi ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

Controlling various divs with unique identifiers using Angular

Imagine having a vast number of HTML elements with unique IDs that require their styles to be changed repeatedly in a controller for spectrum visualization. What is the most efficient way to achieve this in Angular, without resorting to duplicative HTML co ...

Is it common practice to include a variable in a function with the same name as the function itself?

Is it common practice to use a variable with the same name as the function within the function itself? const sum = function(arr) { let sum = 0; for(let i = 0; i < arr.length; i++) sum += arr[i]; return sum; }; Although this code runs s ...

Variations in CSS behavior for select and option elements

I have implemented the following HTML code snippet: <select ...> <option value=""></option> <option data-ng-repeat="type in xy" value="{{type.name}}" ng-style="{'border-left': '4px solid '+ type.color, &apos ...

What causes the return of 'undefined' during the execution of type coercion?

Can you explain why the type of a variable changes but the value remains undefined when trying to set it? let average; // Do I need to initialize with 'average = 0;' for it to work properly? for (const [oddName, odd] of Object.entries(game.odd ...

I am facing difficulty in navigating to a different component

App.js import './App.css'; import CreateBug from './CreateBug'; import { BrowserRouter as Route, Routes } from 'react-router-dom'; import Button from '@mui/material/Button'; import { useNavigate } from "react-ro ...