Definition
A Button is defined as any element that visually resembles a button, this includes internal links that are actually anchor elements but visually look like buttons.
Implementation
The <Button> component can be rendered as either an HTML <button> element or an <a> (anchor) element based on its props. This provides flexibility for different use cases while maintaining a consistent appearance.
Usage
- When to Use:
- Standard Button: If no href prop is provided, the <Button> component will render as a native HTML <button> element. This should trigger actions like dialogs, popovers and form submission.
- Link Button: If an href prop is provided, the <Button> component will render as an HTML <a> element, making it behave like a hyperlink. This should be used to navigate to external links.
Code sample
A basic implementation of the <Button> component looks like this.
Rendering as a standard button
import Button from './Button';
function App() {
return <Button>Click Me</Button>;
}
Rendering as a link button
import Button from './Button';
function App() {
return <Button href="https://example.com">Go to Example</Button>;
}
Sample implementation
const Button = ({ href, className, children, ...props }) => {
if (href) {
// Render as an anchor element
return (
<a href={href} className={`button ${className}`} {...props}>
{children}
</a>
);
}
// Render as a button element
return (
<button className={`button ${className}`} {...props}>
{children}
</button>
);
};