Skip to content

Commit

Permalink
chore: JS for new control component
Browse files Browse the repository at this point in the history
  • Loading branch information
zstix committed Jun 8, 2021
1 parent 409a703 commit 743fb7f
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/components/SegmentedControl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';

const get = (x, key) =>
Object.prototype.hasOwnProperty.call(x, key) ? x[key] : x;

const SegmentedControl = ({ items, onChange }) => {
const [selected, setSelected] = useState(get(items[0], 'value'));

return (
<div>
{items.map((item, index) => {
const value = get(item, 'value');

return (
<button
type="button"
key={index}
tabIndex={index}
value={value}
aria-pressed={selected === value}
disabled={item.disabled}
onClick={(e) => {
setSelected(value);
onChange && onChange(e, value);
}}
>
{get(item, 'label')}
</button>
);
})}
</div>
);
};

SegmentedControl.propTypes = {
/** A callback function that is called whenever the user changes the value. */
onChange: PropTypes.func,

/** Either a list of strings or a list of objects with a value and an optional
label and disabled status. */
items: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.arrayOf(
PropTypes.shape({
value: PropTypes.string.isRequired,
label: PropTypes.string,
disabled: PropTypes.bool,
})
),
]).isRequired,
};

export default SegmentedControl;

0 comments on commit 743fb7f

Please sign in to comment.