简体   繁体   中英

React remove column from table

Here, I have created an application to add a number of row and column dynamically.

I want to remove created column on remove click, I tried many things but, nothing works for me.

When I added column remove button it also stops my row delete functionality.

Here my working example: (In this example I have given static value but, originally it has value given using user input )

Working code:

https://codesandbox.io/s/kk0rn33wqr

//Remove column handler
onRemoveEvent = id => {
   alert(id);

   this.setState({
      //rowCount
    });
};


//Here created remove button
class Table extends Component {
  render() {
      let rowCount = this.props.rowCount;
      let numberOfColumn = this.props.numberOfColumn;
      return (
        <div id="Table">
          <table>
            <tr>{
                Array.from({length: numberOfColumn}).map((_, removeIdx) => (
                  <td>
                    <button onClick={() => this.onRemoveEvent(removeIdx)}>Remove</button>
                  </td>
                ))}
            </tr>

            {rowCount}
          </table>
        </div>
      );
    }
  }

Any help would greatly be appreciated.

I cobbled this together along the same lines as your code. I hope it's useful.

 function Thead({ n, handleColumn }) { const arr = []; for (let i = 0; i < n; i++) { arr.push(<td><button onClick={() => handleColumn(i)}>Remove</button></td>); } return <thead>{arr}</thead>; } function Row({ row, i, handleRow }) { return ( <tr> {row.map(cell => <td>{cell}</td>)} <td><button onClick={() => handleRow(i)}>x</button></td> </tr> ) } class Table extends React.Component { constructor(props) { super(props); this.state = { data: props.data }; this.handleColumn = this.handleColumn.bind(this); this.handleRow = this.handleRow.bind(this); } handleColumn(n) { const newData = this.state.data.map(row => { return row.filter((el, i) => i !== n); }); this.setState({ data: newData }); } handleRow(n) { const newData = this.state.data.filter((el, i) => i !== n); this.setState({ data: newData }); } render() { return ( <table> <Thead n={this.state.data[0].length} handleColumn={this.handleColumn} /> <tbody> {this.state.data.map((row, i) => <Row row={row} i={i} handleRow={this.handleRow} />)} </tbody> </table> ) } } const data = [ [1, 2, 3], [2, 2, 3], [3, 2, 3] ] ReactDOM.render( <Table data={data} />, document.getElementById('container') ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM