etranz
etranz

Reputation: 1253

how to hide column if showColumn state is true

I am rendering a table in react using antd

I am trying to show column if the showColumn state is true and hide the column when it is false

const menuColumns = [
    {
        title: "Date",
        dataIndex: "createdAt",
        key: "createdAt",
        render: (_, { createdAt }) => (
            <>
                <Moment format="D MMM, YY">{createdAt}</Moment>
            </>
        ),
    },
    {
        title: "Action",
        dataIndex: "",
        key: "",
        className: showColumn ? "show" : "hide",
        render: record => (
            <>
                {!record.kitchen_received ?
                    <Button type="primary" onClick={() => showModal(record)}>
                        Delivered
                    </Button> : <i className='bi-check-lg'></i>}
            </>
        ),
    },
];

Upvotes: 0

Views: 128

Answers (2)

leo
leo

Reputation: 111

You can potentially just avoid to add the whole column to menuColumns if you don't need to add it? So something like this?

const menuColumns = [
    {
        title: "Date",
        dataIndex: "createdAt",
        key: "createdAt",
        render: (_, { createdAt }) => (
            <>
                <Moment format="D MMM, YY">{createdAt}</Moment>
            </>
        ),
    },
    (showColumn ? {
        title: "Action",
        dataIndex: "",
        key: "",
        render: record => (
            <>
                {!record.kitchen_received ?
                    <Button type="primary" onClick={() => showModal(record)}>
                        Delivered
                    </Button> : <i className='bi-check-lg'></i>}
            </>
        ),
    } : {})
];

Or based on the way you set it up with classNames you can just display none when the column has the hide class applied?

Upvotes: 2

Korotkevich
Korotkevich

Reputation: 61

The solution @leo gave would also work. Alternatively, you can keep the column in state and update the state by pushing the required column on click, dynamically. This method can help you push columns with dynamic properties which you can pass onClick. For ex: The user has the option to select a different number of fruits and you want to show the fruit name as the column.

To hide them: You can simply delete them from the state.

Upvotes: 0

Related Questions