| 1 |
import React, { useEffect } from "react"; |
| 2 |
import ButtonLinkNoUrlError from "../inc/err/ButtonLinkNoUrlError"; |
| 3 |
|
| 4 |
/** |
| 5 |
* Button link type. |
| 6 |
* |
| 7 |
* @type {{TEXT: string, PRIMARY: string, DEFAULT: string}} |
| 8 |
*/ |
| 9 |
export const ButtonLinkType = { |
| 10 |
TEXT: "text", |
| 11 |
DEFAULT: "default", |
| 12 |
PRIMARY: "primary", |
| 13 |
}; |
| 14 |
|
| 15 |
/** |
| 16 |
* Button link component. |
| 17 |
* |
| 18 |
* @param {Object} props component properties |
| 19 |
* @param {string} props.url target url |
| 20 |
* @param {Function} props.onClickHandler click handler callback, if provided, url direction will be ignored |
| 21 |
* @param {string} props.type button link type, should be one of ButtonLinkType object values |
| 22 |
* @param {string} props.title button title |
| 23 |
* @class |
| 24 |
*/ |
| 25 |
function ButtonLink({ |
| 26 |
title, |
| 27 |
url = null, |
| 28 |
onClickHandler = null, |
| 29 |
type = ButtonLinkType.DEFAULT, |
| 30 |
}) { |
| 31 |
/** |
| 32 |
* useEffect hook. |
| 33 |
*/ |
| 34 |
useEffect(() => { |
| 35 |
if (!url && !onClickHandler) { |
| 36 |
throw new ButtonLinkNoUrlError(); |
| 37 |
} |
| 38 |
}, []); |
| 39 |
|
| 40 |
/** |
| 41 |
* Redirect to component url. |
| 42 |
*/ |
| 43 |
const redirect = () => { |
| 44 |
window.open(url, "_blank"); |
| 45 |
}; |
| 46 |
|
| 47 |
/** |
| 48 |
* Button clicked logic. |
| 49 |
* |
| 50 |
* @param {Event} e click event |
| 51 |
*/ |
| 52 |
const buttonClicked = e => { |
| 53 |
if (onClickHandler && typeof onClickHandler === "function") { |
| 54 |
onClickHandler(e); |
| 55 |
} else { |
| 56 |
redirect(); |
| 57 |
} |
| 58 |
}; |
| 59 |
|
| 60 |
return ( |
| 61 |
<div |
| 62 |
className={"tableberg-button-link"} |
| 63 |
data-buttonlink-type={type} |
| 64 |
onClick={buttonClicked} |
| 65 |
role={"button"} |
| 66 |
> |
| 67 |
{title} |
| 68 |
</div> |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* @module ButtonLink |
| 74 |
*/ |
| 75 |
export default ButtonLink; |
| 76 |
|