Overnap

UserRole 컴포넌트 추가

1 +import React, { useCallback, useContext, useEffect, useState } from 'react';
2 +import SocketContext from '../../contexts/SocketContext';
3 +import { MessageType, RawMessage } from '../common/types';
4 +import { RoleData, RoundData } from './types';
5 +
6 +interface UserRoleProps {
7 + isInGame: boolean;
8 +}
9 +
10 +export const UserRole: React.FC<UserRoleProps> = ({ isInGame }) => {
11 + const socket = useContext(SocketContext);
12 + const [ roles, setRoles ] = useState<RoleData[]>([]);
13 +
14 + const handleRole = useCallback((rawMessage: RawMessage) => {
15 + if (rawMessage.type === MessageType.GAME_START) {
16 + const { roles } = rawMessage.message as RoundData;
17 + setRoles(roles);
18 + }
19 + }, []);
20 +
21 + useEffect(() => {
22 + socket.on('msg', handleRole);
23 + return () => {
24 + socket.off('msg', handleRole);
25 + }
26 + }, []);
27 +
28 + return (
29 + <div className={`w-40 h-144 rounded shadow flex flex-col items-center ${isInGame ? '' : 'hidden'}`}>
30 + <div className='mt-3' />
31 + {roles.map(x => (
32 + <div key={x.username} className={`my-5 ease-linear transition-all duration-100
33 + ${x.role === 'drawer' ? 'text-blue-500'
34 + : x.role === 'winner' ? 'text-green-500'
35 + : 'text-black'}`}>
36 + {x.nickname} {x.role === 'drawer' ? '🖌️' : x.role === 'spectator' ? '👻' : ''}
37 + </div>
38 + ))}
39 + </div>
40 + );
41 +}