telekom / scale

Scale is the digital design system for Telekom products and experiences.
https://telekom.github.io/scale/
Other
372 stars 82 forks source link

Implementing Checkbox Toggle with Scale Components in React Data Grid #2152

Open henrisco82 opened 11 months ago

henrisco82 commented 11 months ago

Scale Version "@telekom/scale-components": "^3.0.0-beta.132", "@telekom/scale-components-react": "^3.0.0-beta.132"

Framework and version React "react": "^17.0.2"

Screenshot 2023-09-29 at 10 10 59 AM

Hello there,

I am trying to use a checkbox (switch) on data grid component in react that displays a list of users. I would like to be able to toggle the switch to activate or deactivate a user by calling a function. In other words, I will like to be able to respond to event when the switch(checkbox) is changed. I have tried using event handlers like onClick, onChange, onScaleChange but the function is not triggered. Please is there a way I can achieve this with Scale?

I have tried implementing it the following way

const rows = activatedUsers.map((user) => ([
    user.email,
    user.roles,
      [{
          label: 'Activate',
          type: 'checkbox',
          onChange: () => {
            console.log('User Activation function here');
          },
        }]
  ]));

  const cols = [
    {
      label: 'Email',
    },
    {
      label: 'Role',
    },
    {
      type: 'checkbox',
      label: 'Activate',
      style: 'switch',
      editable: true,
      sortable: true,
    },
  ];

I have also noticed that the heading is the same as label of the switch. Is it possible to decouple them from each other?

Thanks a lot.

felix-ico commented 11 months ago

Hi @henrisco82, sorry for the late reply.

I'm not sure the checkbox field should be set like that, looking at the docs https://telekom.github.io/scale/?path=/docs/components-data-grid--checkbox-cell the checkbox field is just a boolean (true for active), and not a complex object like in your code snippet. So your rows should be defined as follows:

const rows = activatedUsers.map((user) => ([
    user.email,
    user.roles,
    // if user object has an active property you could do:
    // user.active ? true : false
    // judging by the mapped array name 'activeUsers' i guess they can only be deactivated
    true

The scale-change event listener should be set on the ScaleDataGrid (or on window/document), so it would look something like this:

<ScaleDataGrid
    ...
    onScaleChange={() => {console.log('changed', rows}}
>

and this should log the rows with the updated values (when switched off they will be false).

I based my answer on https://github.com/telekom/scale/issues/811 a little, where a somewhat similar issue was described, perhaps that can help you too.

Regarding the switch label, this seems not possible with the current implementation, and adding this would be a feature request (btw scale users are always welcome to open pull requests for such improvements 🤓).