QuickChess/src/index.js

93 lines
1.9 KiB
JavaScript

import React from 'react';
import ReactDOM from 'react-dom';
import io from 'socket.io-client';
import Board from './board';
import './index.css';
const ENDPOINT = "http://localhost:5000";
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onSubmit = props.onSubmit;
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
this.onSubmit(this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
board: null,
socket: io(ENDPOINT),
gameKey: null,
};
this.state.socket.on("FromAPI", data => {
console.log(data);
this.setState({
board: null,
});
this.setState({
board: (
<Board
text={data}
onMove={(move) => {
console.log("ON MOVE");
this.state.socket.emit("move", this.state.gameKey, move);
}}/>
),
});
});
}
setGameKey(key) {
console.log(`Setting gameKey to '${key}'`);
this.setState({gameKey: key});
this.state.socket.emit("find", key);
}
render() {
return (
<div className="game">
<div className="game-board">
{this.state.gameKey ? this.state.board : <NameForm onSubmit={this.setGameKey.bind(this)} />}
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);