| 1 |
import { useState } from 'react'; |
| 2 |
import { LabelGroup, Label, LabelColor } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
export const LabelGroupEditableAdd: React.FunctionComponent = () => { |
| 5 |
const [idIndex, setIdIndex] = useState<number>(3); |
| 6 |
const [labels, setLabels] = useState<any>([ |
| 7 |
{ name: 'Label 1', id: 0 }, |
| 8 |
{ name: 'Label 2', id: 1 }, |
| 9 |
{ |
| 10 |
name: 'Label 3', |
| 11 |
props: { |
| 12 |
isEditable: true, |
| 13 |
editableProps: { |
| 14 |
'aria-label': 'Editable label with text Label 3' |
| 15 |
} |
| 16 |
}, |
| 17 |
id: 2 |
| 18 |
} |
| 19 |
]); |
| 20 |
|
| 21 |
const onClose = (labelId: string) => { |
| 22 |
setLabels(labels.filter((l: any) => l.id !== labelId)); |
| 23 |
}; |
| 24 |
|
| 25 |
const onEdit = (nextText: string, index: number) => { |
| 26 |
const copy = [...labels]; |
| 27 |
const updatedProps = { |
| 28 |
...labels[index].props, |
| 29 |
editableProps: { 'aria-label': `Editable label with text ${nextText}` } |
| 30 |
}; |
| 31 |
|
| 32 |
copy[index] = { name: nextText, props: updatedProps, id: labels[index].id }; |
| 33 |
setLabels(copy); |
| 34 |
}; |
| 35 |
|
| 36 |
const onAdd = () => { |
| 37 |
setLabels([ |
| 38 |
{ |
| 39 |
name: 'New Label', |
| 40 |
props: { |
| 41 |
isEditable: true, |
| 42 |
editableProps: { |
| 43 |
'aria-label': `Editable label with text New Label` |
| 44 |
} |
| 45 |
}, |
| 46 |
id: idIndex |
| 47 |
}, |
| 48 |
...labels |
| 49 |
]); |
| 50 |
setIdIndex(idIndex + 1); |
| 51 |
}; |
| 52 |
|
| 53 |
return ( |
| 54 |
<LabelGroup |
| 55 |
categoryName="Label group 1" |
| 56 |
numLabels={5} |
| 57 |
isEditable |
| 58 |
addLabelControl={ |
| 59 |
<Label variant="add" onClick={onAdd}> |
| 60 |
Add label |
| 61 |
</Label> |
| 62 |
} |
| 63 |
> |
| 64 |
{labels.map((label, index) => ( |
| 65 |
<Label |
| 66 |
key={label.id} |
| 67 |
id={label.id} |
| 68 |
color={LabelColor.blue} |
| 69 |
onClose={() => onClose(label.id)} |
| 70 |
onEditCancel={(_event, prevText) => onEdit(prevText, index)} |
| 71 |
onEditComplete={(_event, newText) => onEdit(newText, index)} |
| 72 |
{...label.props} |
| 73 |
> |
| 74 |
{label.name} |
| 75 |
</Label> |
| 76 |
))} |
| 77 |
</LabelGroup> |
| 78 |
); |
| 79 |
}; |