Rich
Rich

Reputation: 185

Ant Design for React : Show/Hide particular column

I need a bit of help here, In an Ant Design table, I need to hide/show a particular column of a table depending on a state value. In the given sandbox link, I need to hide the surname column whenever the switch is Off and show when the switch is On.

Please, someone, look into this, and help me out.

Reference: https://codesandbox.io/s/purple-sun-1rtz1?file=/index.js

Upvotes: 0

Views: 3920

Answers (1)

Peter
Peter

Reputation: 1259

There is a working code, but it should be more customize, interactivize, and refactorize depending on your need:

// You can also modify the data in the `handleChnage`
// Or conditionally display it like here:

class EditableTable extends React.Component {
  state = {
    surNameShow: false
  };
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "Name",
        dataIndex: "name",
        width: "30%"
      },
      {
        title: "Surname",
        dataIndex: "surname",
        width: "30%"
      }
    ];
    this.state = {
      dataSource: [
        {
          key: "0",
          name: "Edward 1",
          surname: "King 1"
        },
        {
          key: "1",
          name: "Edward 2",
          surname: "King 2"
        }
      ]
    };
  }
  handleChnage = key => {
    this.setState({ surNameShow: !this.state.surNameShow }, () => {
      console.log(this.state.surNameShow);
    });
  };

  render() {
    const { dataSource } = this.state;
    const columns = this.columns;
    return (
      <div>
        <p className="mr-3"> Show surname</p>
        <Switch onChange={() => this.handleChnage()} />
        <Table
          bordered
          dataSource={dataSource}
          columns={
            this.state.surNameShow
              ? columns
              : columns.filter(ea => ea.dataIndex !== "surname")
          }
          pagination={false}
        />
      </div>
    );
  }
}

ReactDOM.render(<EditableTable />, document.getElementById("container"));

Upvotes: 4

Related Questions