JSFiddle - React, Tailwind, and code Playground
by cirossmonteiro
HTML
<div id = "app"></div>
CSS
div.square {
display: inline-block;
width: 20px;
height: 20px;
text-align: center;
vertical-align: top;
border-style: solid;
border-width: 1px;
/*margin-bottom: -5px;*/
/*margin: 0px;*/
}
div.marked {
background-color: yellow;
}
JavaScript
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {clicked : false, keydown : 0};
this.handleClick = this.handleClick.bind(this);
this.handleKey = this.handleKey.bind(this);
}
handleKey(e) {
this.setState({keydown : e.which});
}
handleClick() {
this.props.onCoord(this.props.i, this.props.j);
if (this.state.clicked == true){
this.setState({clicked : false});
this.setState({keydown : 0});
}
else {
this.setState({clicked : true});
}
}
render () {
var text = "";
if (this.state.clicked == true) {
if (this.state.keydown != 0) {
text = String.fromCharCode(this.state.keydown);
}
}
if(this.props.marked == 1) {
return (<div className = "square marked" tabIndex = "0" onKeyDown = {this.handleKey} onClick = {this.handleClick}>{text}</div>);
}
else {
return (<div className = "square" tabIndex = "0" onKeyDown = {this.handleKey} onClick = {this.handleClick}>{text}</div>);
}
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {keydown : 0, coord : [-1,-1]};
this.handleKey = this.handleKey.bind(this);
this.handleCoord = this.handleCoord.bind(this);
}
handleKey(e) {
this.setState({keydown : e.keycode});
}
handleCoord(i,j) {
//alert(String(i)+" "+String(j));
this.setState({coord : [i,j]});
//alert(String(this.state.coord[0])+" "+String(this.state.coord[1]));
}
render() {
var ret = [];
//ret.push(<div>);
for (var i = 0; i < this.props.m; i++) {
for (var j = 0; j < this.props.n; j++) {
if (i == this.state.coord[0] && j == this.state.coord[1]) {
ret.push(<Square marked = "1" onCoord = {this.handleCoord} i = {i} j = {j} />);
}
else {
ret.push(<Square marked = "0" onCoord = {this.handleCoord} i = {i} j = {j} />);
}
}
...