QuickChess/src/index.js

93 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-12-27 20:11:50 -05:00
import React from 'react';
import ReactDOM from 'react-dom';
import io from 'socket.io-client';
import Board from './board';
2020-12-27 20:11:50 -05:00
import './index.css';
2021-01-06 12:05:57 -05:00
const ENDPOINT = "http://localhost:4001";
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>
);
}
}
2020-12-27 20:11:50 -05:00
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
board: null,
socket: io(ENDPOINT),
2021-01-06 12:05:57 -05:00
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");
2021-01-06 12:05:57 -05:00
this.state.socket.emit("move", this.state.gameKey, move);
}}/>
),
});
});
}
2021-01-06 12:05:57 -05:00
setGameKey(key) {
console.log(`Setting gameKey to '${key}'`);
this.setState({gameKey: key});
this.state.socket.emit("find", key);
}
2020-12-27 20:11:50 -05:00
render() {
return (
<div className="game">
<div className="game-board">
2021-01-06 12:05:57 -05:00
{this.state.gameKey ? this.state.board : <NameForm onSubmit={this.setGameKey.bind(this)} />}
</div>
2020-12-27 20:11:50 -05:00
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);