5

so I worked on a project using react js with umi js and antd as additional dependencies,

I had a problem when I got the task to disable each row in the antd table,

I tried to read the documentation antd but got nothing,

is it possible that you can do that? or there is another possible way to doing that

Thank you for the help

here's my code :

/* eslint-disable */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Button, Select, message, Radio, Table, Alert } from 'antd';
import _       from 'lodash';
import axios   from 'axios';
import cookies from 'js-cookie';
import {_getCurrentBusiness} from '../../../utils/utils_business';
import {formatMessage }     from 'umi-plugin-locale';

function DeleteConfirm (props) {

    const user_auth           = cookies.getJSON('ckmsbp');
    const business            = _getCurrentBusiness();
    const [radio, setRadio]   = useState('all');
    const [role, setRole]     = useState(null);
    const [chRole, setChrole] = useState(null); //changerole
    const [btn, setBtn]       = useState(false);
    const isMounted           = useRef(null);
    const roleRef             = useRef(null);
    const spanAmount          = {fontSize: '1rem', fontWeight: 500,marginLeft: '1rem'}

    useEffect( () => {
        isMounted.current = true;
        return () => isMounted.current = false;
    }, [])
    useEffect( () => {
        if(!_.isNil(props.roles)) {
            const updateRole = _.filter(props.roles, r => !_.eq(r.id, props.role.id) );           
            setRole(updateRole); //tampil di select 
        }
    }, [props.roles]);

    const handleSubmit = async () => {
        let   accountMeta = {}
        const body        = {status: 'deleted'}
        const params      = { _id: props.role.id}
        console.log('radio', radio);
        if(_.eq(radio, 'all')){

            if(_.isNil(chRole)) {
                message.error('data can not empty')
                props.chVisible(null); //close modal
            }

            _.forEach(props.account, async acc => {
                let bus = [];
                if( !_.isNil(acc.business) && _.isString(acc.business) ) bus = JSON.parse(acc.business);
                const find = _.findIndex(bus, b => {
                    return _.eq(b._id, business._id) && _.eq(b.role_capability, props.role.id)
                })
                bus[find].role_capability = chRole;
                acc.business = JSON.stringify(bus)
                accountMeta = {
                    value     : acc.business,
                    key       : 'business',
                    account_id: acc._id
                }
                await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token}});
            })

        } else if( _.eq(radio, 'manual')){
            console.log('asd');

        } else if (_.eq(radio, 'delete')){
            _.forEach(props.account, async acc => {
                let bus = [];
                if( !_.isNil(acc.business) && _.isString(acc.business) ) bus = JSON.parse(acc.business);
                const find = _.findIndex(bus, b => _.eq(b._id, business._id) && _.eq(b.role_capability, props.role.id) )
                if(_.gt(find, -1)){
                    acc.business = JSON.stringify([])
                    accountMeta = {
                        value     : acc.business,
                        key       : 'business',
                        account_id: acc._id
                    }
                    await axios.put(`${API}/account-meta`, accountMeta, { headers: { Authorization: user_auth.token}});
                }                
            })
        }
         const deleteResult = await axios.put(`${API}/master`, body, { params, headers: { Authorization: user_auth.token}});
         if(!_.isNil(deleteResult) && _.isObject(deleteResult.data)){
             let no         = 1;
             let data       = []
             let updateRole = _.filter(props.roles, r => !_.eq(r.id, props.role.id));
             _.map(updateRole, role => {
                 role.no = no;
                 data.push(role)
                 no++
             });
             props.data(data); //tampil di select 
             message.success('data updated!')
             props.chVisible(null); //close modal
         }
    }

    const onChange  = (data) => {
        const value = data.target.value
        setRadio(value);
    }

    const roleChange = (data) => {
        setChrole(data)
    }

    //props column diambil dari datasource
    const columns = [
      {
        title    : 'No',
        dataIndex: 'no',
        key      : 'no',
      },
      {
        title    : 'Account\'s Name',
        dataIndex: 'name',
        key      : 'name',
      },
      {
        title    : 'Change Role',
        dataIndex: 'id',
        key      : 'action',
        render : (text, data) => renderButton(text, data) 
      },
    ];

    const handleClick = (e, data) => {
        setBtn(!btn)
        console.log('e', e);
        console.log('data', data);
    }

    const rowClassName = (record, index) => {
        console.log('record', record);
        console.log('index',index);

    }

    const renderButton = () => {
      let arrayAllow = [];
        arrayAllow.push(
          <Select
                showSearch
                key              = '1'
                size             = "small"
                placeholder      = "select"
                ref              = {roleRef}
                optionFilterProp = "children"
                style            = {{ width: 100 }}
                onChange         = {(e) => roleChange(e)} //handle change role
                filterOption     = {(input, option) => _.toLower(option.props.children).indexOf(_.toLower(input)) >= 0}
            >
                {
                    !_.isNil(role) && _.map(role, (newVal) => {
                        return (<Select.Option 
                                    key   = {newVal.id}
                                    title = {newVal.title}
                                    value = {newVal.id}>{newVal.title}
                                </Select.Option>)
                    })
                }
            </Select>
        )
        arrayAllow.push( <Button 
                            type    = {!btn ? "danger" : "primary"}
                            key     = '2'
                            icon    = {!btn ? "close" : "redo"}
                            size    = "small"
                            onClick = {(e) => handleClick(e, props.role.id)}
                         /> )
      return arrayAllow
    }

    // R E N D E R I N G
    return(
      <div>
        <Modal
            title    = {`${formatMessage({id: 'ROLE_MANAGEMENT.DELETE_CONFIRM_TITLE'})} ${props.role.title}`}
            visible  = {props.visible}
            onOk     = {() => handleSubmit()}
            onCancel = {() => props.cancel(null) }
            width    = {800}
        >
          <p>{formatMessage({id : 'ROLE_MANAGEMENT.DELETE_CONFIRM_STATEMENT', title: props.role.title})}</p>
            <div style={{marginBottom: '1rem'}}>
                <Radio.Group onChange = {(e) => onChange(e)} value={radio}>
                    <Radio value="all"   >Changed All of people  </Radio>
                    <Radio value="manual">Changed people manually</Radio>
                    <Radio value="delete">Total delete           </Radio>
                </Radio.Group>
            </div>

          { _.eq(radio, 'all') && 
            <div>
                <Select
                    showSearch
                    ref              = {roleRef}
                    size             = "large"
                    style            = {{ width: 200 }}
                    placeholder      = {formatMessage({id: 'ACCOUNT.PLCHOLDER_ROLE'})}
                    optionFilterProp = "children"
                    onChange         = {(e) => roleChange(e)} //handle change role
                    filterOption     = {(input, option) => _.toLower(option.props.children).indexOf(_.toLower(input)) >= 0}
                >
                    {
                        !_.isNil(role) && _.map(role, (newVal) => { 
                            return ( <Select.Option 
                                        key   = {newVal.id}
                                        title = {newVal.title}
                                        value = {newVal.id}
                                     >{newVal.title}
                                     </Select.Option> )
                        })
                    }
                </Select>
                <span style={spanAmount}>{`Total amount of people which have role ${props.role.title} : ${_.size(props.account)}`}</span>
            </div>
          }

          { _.eq(radio, 'manual') && <Table 
                                        dataSource   = {props.account}
                                        rowClassName = {rowClassName}
                                        columns      = {columns}
                                        pagination   = {{ pageSize: 50 }}
                                        scroll       = {{ y: 250 }}
                                    /> 
          }

          { _.eq(radio, 'delete') && <Alert
              message     = "Attention!"
              description = {formatMessage({id: 'ROLE_MANAGEMENT.DELETE_CONFIRM_DELETE'})}
              type        = "warning"
              showIcon
            />
          } 
        </Modal>
      </div>
    )
}

export default DeleteConfirm;

*the picture that I intend to disable when clicked on the danger button enter image description here

Heru Wijayanto
  • 439
  • 3
  • 5
  • 16
  • Do you want to delete the row basically do you want to remove the row from the data or do you want to show the row but some how the user should understand it is disabled If its the second case Even i was also figuring out this issue so as a workaround i have added a class name based on the condition so for your case when click on close button the disabled property will be changing from false to true for that particular row so based on that property you can add a className and disable the row by adding some css that looks disabled . let me know if this is what you are looking for – Learner Jan 03 '20 at 07:30
  • thanks in advance for the response, so what I want from this modal appears, when the admin (executor) wants to delete the role and the system detects that there is a used account, the admin chooses it manually, and must replace the account with another role * contained in the select component * and when the red button is pressed then the red button is replaced by another button and the line is disabled but not with the button because it can still be executed like toogle true / false – Heru Wijayanto Jan 03 '20 at 07:56
  • 1
    so basically the row should be disabled not deleted am i correct, so you can add a className and do the css – Learner Jan 03 '20 at 08:39
  • yes you are right... thanks to advance, ill try my best then.. – Heru Wijayanto Jan 03 '20 at 09:16
  • sure no issues, i will add a sample snippet for this one so you can refer and use the same logic – Learner Jan 03 '20 at 09:46
  • ok sir, ill be waiting.. terima kasih :) – Heru Wijayanto Jan 03 '20 at 10:05
  • Added the code snippet you can use the same logic to solve the issue, happy coding – Learner Jan 03 '20 at 10:19

1 Answers1

9

In Antd there is no simple way to disable a row, so you can do it as workaround like below

So basically when you click on close button you can have state whether its been enabled or disabled as a boolean value

so each record will have that key. so based on that you can add a className and style it as disabled.

Here is a sample code snippet

App.js

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Table } from "antd";

import "./styles.css";

function App() {
  const dataSource = [
    {
      key: "1",
      name: "Mike",
      age: 32,
      address: "10 Downing Street",
      enabled: true
    },
    {
      key: "2",
      name: "John",
      age: 42,
      address: "10 Downing Street",
      enabled: false
    }
  ];

  const columns = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name"
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age"
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address"
    }
  ];
  return (
    <>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowClassName={record => !record.enabled && "disabled-row"}
      />
      ;
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

style.css

.disabled-row {
  background-color: #dcdcdc;
  pointer-events: none;
}

I hope this way you will have better understanding of solving the problem

Working codesandbox

Learner
  • 8,379
  • 7
  • 44
  • 82