E
E
evg_962018-02-15 08:23:43
JavaScript
evg_96, 2018-02-15 08:23:43

How to handle clicking on any cell in a table?

There is a table (field) for playing the Japanese crossword puzzle. There is a table data model - a two-dimensional array. 0 is an empty cell, 1 is not empty. Initially, everything is filled with zeros.
How, when you click on a cell, check its value, and if 0 then change it in state to 1, otherwise to 0?

class Field extends React.Component {
  constructor() {
    super();

    this.handleTdClick = this.handleTdClick.bind(this);
  }

  handleTdClick(item) {
    // проверка и изменение значений в состоянии
   // к значению есть доступ, а вот как получить доступ к самой ячейки, чтобы изменить ей класс, не понятно
  }

  render() {
    const { rows } = this.props;

    return (
      <table className="field">
        <tbody>
          {
            rows.map((row, index) => (
              <tr key = { index }>
                {
                  row.map((item, index) => (
                    item !== 0
                    ? <td
                        onClick = { this.handleTdClick.bind(this, item) }
                        key = { index }
                        className="not-empty">
                      </td>
                    : <td
                        onClick = { this.handleTdClick.bind(this, item)  }
                        key = { index }
                        className="empty">
                      </td>
                  ))
                }
              </tr>
            ))
          }
        </tbody>
      </table>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2018-02-15
@evg_96

how to access the cell itself to change its class
You don’t need to receive in any way, you must hang all classes in render () based on the data, this is the whole point of React. In the handler, you change the state, render () is automatically called, the new state is unloaded into the DOM. You work with data, React works with DOM.

D
Dmitry Alekseev, 2018-02-15
@Zatmil

If I understand you correctly, then
onClick={(e) => this.handleTdClick(e, item)}

N
Ninja Mate, 2018-02-15
@victorzadorozhnyy

import createReactClass from 'create-react-class'
const Td = createReactClass({
  render () {
    return (
                   <td
                        onClick = { this.props.handleTdClick(item, e) }
                        key = { this.props.index }
                        className={this.props.item.state ===1 "empty" ? "not-empty" :}>
                   </td>
...
<Td {...props} />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question