Skip to content

Commit db09dc0

Browse files
Markus Hatvantaion
Markus Hatvan
authored andcommitted
feat: Add the as prop to Badge to support actionable badges (react-bootstrap#4295)
* feat: support actional bagdes by adding the as property to the Badge component (react-bootstrap#4227) * add 'as' prop to Badge.js * add unit test that verifies 'as' prop is working Signed-off-by: mhatvan <[email protected]> * * updated type definitions & simple.test.tsx for Badge Signed-off-by: mhatvan <[email protected]> * feat: added another TS test case * fix: closing tag * fix: prettier
1 parent e8f20f5 commit db09dc0

File tree

4 files changed

+24
-5
lines changed

4 files changed

+24
-5
lines changed

src/Badge.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,23 @@ const propTypes = {
2020
* some additional horizontal padding
2121
*/
2222
pill: PropTypes.bool.isRequired,
23+
24+
/** @default span */
25+
as: PropTypes.elementType,
2326
};
2427

2528
const defaultProps = {
2629
pill: false,
2730
};
2831

2932
const Badge = React.forwardRef(
30-
({ bsPrefix, variant, pill, className, ...props }, ref) => {
33+
(
34+
{ bsPrefix, variant, pill, className, as: Component = 'span', ...props },
35+
ref,
36+
) => {
3137
const prefix = useBootstrapPrefix(bsPrefix, 'badge');
3238
return (
33-
<span
39+
<Component
3440
ref={ref}
3541
{...props}
3642
className={classNames(

test/BadgeSpec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,12 @@ describe('Badge', () => {
1515
.text(),
1616
).to.equal('Message');
1717
});
18+
19+
it('should support custom `as`', () => {
20+
mount(
21+
<Badge as="a" href="#" variant="primary" pill>
22+
Message
23+
</Badge>,
24+
).assertSingle('a[href="#"]');
25+
});
1826
});

types/components/Badge.d.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as React from 'react';
2+
import { BsPrefixComponent } from './helpers';
23

3-
export interface BadgeProps extends React.HTMLProps<HTMLSpanElement> {
4+
export interface BadgeProps {
45
bsPrefix?: string;
56
variant?:
67
| 'primary'
@@ -14,6 +15,8 @@ export interface BadgeProps extends React.HTMLProps<HTMLSpanElement> {
1415
pill?: boolean;
1516
}
1617

17-
declare const Badge: React.ForwardRefExoticComponent<BadgeProps>;
18+
declare class Badge<
19+
As extends React.ElementType = 'span'
20+
> extends BsPrefixComponent<As, BadgeProps> {}
1821

1922
export default Badge;

types/simple.test.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ import {
5454
</Card>
5555
</Accordion>;
5656

57-
<Badge pill={false} ref={React.createRef<HTMLSpanElement>()}>
57+
<Badge pill={false}>42</Badge>;
58+
59+
<Badge as="a" href="#" variant="primary" pill>
5860
42
5961
</Badge>;
6062

0 commit comments

Comments
 (0)