Skip to main content

Button

Overview​

The Button component is a flexible and themable button element that supports custom icons, themes, and additional properties. It integrates with a global theme context and allows merging of local and global themes for consistent styling.

Importing​

To use the Button component, import it:

import Button from './path/to/Button';

Component Signature​

type ButtonProps = {
icon?: React.ReactNode;
type: 'submit' | 'button';
disabled?: boolean;
children: React.ReactNode;
} & ThemePart<'button'>

Props​

  • icon (optional): A React.ReactNode representing an icon to display inside the button.
  • type: Specifies the button type, either 'submit' or 'button'.
  • disabled (optional): A boolean indicating if the button is disabled.
  • children: The content inside the button.
  • theme (optional): A partial theme object used to customize the button's appearance. It merges with the global theme.

How It Works​

  1. Theme Context: The component retrieves the global theme using the useTheme hook.
  2. Theme Merging: The global theme is merged with the local theme and label-specific theme properties using mergeThemeWithPT.
  3. Rendering:
    • The icon is displayed within a <span> if provided.
    • The children are rendered inside a <span> styled with the merged theme's label properties.
  4. Props Filtering: The type and disabled properties are passed directly to the <button> element using partial utility to avoid unnecessary props.

Example Usage​

Basic Button​

import React from 'react';
import Button from './path/to/Button';

const App: React.FC = () => {
return (
<Button type="submit">
Click Me
</Button>
);
};

export default App;

Button with Icon​

import React from 'react';
import Button from './path/to/Button';

const App: React.FC = () => {
return (
<Button type="button" icon={<i className="icon-class" />}>Submit</Button>
);
};

export default App;

Themed Button​

import React from 'react';
import Button from './path/to/Button';

const App: React.FC = () => {
const customTheme = {
root: { className: 'custom-root' },
label: { className: 'custom-label' },
icon: { className: 'custom-icon' },
};

return (
<Button type="button" theme={customTheme}>
Themed Button
</Button>
);
};

export default App;

Best Practices​

  • Icons: Use accessible icons with meaningful labels for better UX.
  • Theming: Leverage the global theme context to ensure a consistent look across the application.
  • Prop Management: Use the partial utility to filter out unnecessary props passed to the <button> element.

Notes​

  • The component uses the useTheme hook to fetch the global theme context.
  • Themes are merged deeply for labels and other sub-components.
  • The button’s type defaults to 'button' if not specified, as per the HTML5 specification.

Contributing​

If you encounter issues or have suggestions for improving the Button component, feel free to contribute or report an issue on the repository.