Search code examples
reactjsantd

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>}
            </>
        ),
    },
];

Solution

  • 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?