carbon-design-system / carbon

A design system built by IBM
https://www.carbondesignsystem.com
Apache License 2.0
7.88k stars 1.82k forks source link

Create a consistent API for event handlers in v11 #9641

Closed joshblack closed 2 years ago

joshblack commented 3 years ago

We would like any on* or event-handler-related props to have consistent API across the codebase. During an initial review, we noticed that several patterns are floating around the codebase that has been developed throughout the years:

Checklist

joshblack commented 3 years ago

Audit

joshblack commented 3 years ago

joshblack commented 3 years ago

Proposal

Controlled components

// A change handler is an `onChange` prop for a controlled component
// This handler is generic over the data/state that is made public by the component.
// It should be of type object so that it is easy to modify/extend with additional values
// in the future
type ChangeHandler<T extends object> = (data: T) => void;

function Example() {
  const [value, setValue] = React.useState('');

  return (
    <Sample
      value={value}
      onChange={(data) => setValue(data.value)}
    />
  );
}

Controlled components with native onChange

In situations where a controlled component may have a native onChange event, we often combine the onChange event with the change handler defined above. This can have several types:

We have several possible directions forward:

The most compelling options seem to be: