Weaverse Hydrogen Components
Weaverse Components are the building blocks of your Hydrogen theme. They combine React’s component model with Weaverse’s powerful schema system to create customizable, performant sections for your storefront. This guide provides a comprehensive overview of how to create, configure, and optimize Weaverse components.Getting Started
Component Registration
To use your components in Weaverse, you need to register them in your application:Core Concepts
What Makes a Weaverse Component?
A Weaverse Component consists of three essential parts:- Component Logic: A React component that renders your UI using TypeScript and modern React patterns
- Schema Definition: Configuration that powers the visual editor in Weaverse Studio
- Data Integration: Optional server-side data fetching for dynamic content
Component Lifecycle
A Weaverse component follows this lifecycle:- Component Creation: Define the component file
- Schema Definition: Configure how the component appears in the editor
- Component Logic: Implement the React component with proper props
- Data Integration: Set up data fetching if needed
- Render: Component is rendered on the page
- Update: Component re-renders when props or state change
- Cleanup: Component unmounts and cleans up resources
Component Structure
Basic Component Architecture
Every Weaverse component follows a consistent structure:- Imports: Import necessary types and utilities from Weaverse and React
- Interface: Define the component’s props interface
- Component: Create the component (with or without
forwardRef
, see note below) - Schema: Export the schema that defines how the component appears in Weaverse Studio
- Export: Export the component as default
Note aboutforwardRef
: While many examples useforwardRef
, it’s actually optional in Weaverse components. It helps pass the ref to the component’s DOM element so that Weaverse Editor can render essential UI elements like overlays and toolbars in the editor. However, if you spread all props to your root DOM element (e.g.,<div {...props}>
), Weaverse will automatically detect the DOM element. Additionally, with React 19,forwardRef
will become less necessary due to improvements in ref handling.
Basic Component Template
Key Elements
- HydrogenComponentProps: Base props interface that all Weaverse components extend
- forwardRef: Used to properly pass refs through the component tree (optional if props are spread correctly)
- type property in schema: Unique identifier for the component (must be unique across all components)
- settings: Defines the UI controls in Weaverse Studio
- children prop: Components can render child components or elements
Advanced Component Structure
For more complex components, you may need to handle data loading, custom styling, or complex props management:Component Types
1. Content Sections
- Hero sections (images, videos)
- Text blocks and rich content
- Media galleries and sliders
- Feature sections
- Testimonial sections
2. E-commerce Components
- Product displays
- Collection grids
- Related products
- Product information
- Cart components
- Checkout components
3. Interactive Elements
- Forms and newsletters
- Reviews and testimonials
- Maps and location displays
- Countdown timers
- Image hotspots
Schema Definition
The schema defines how your component appears and behaves in Weaverse Studio. It provides the configuration for the visual editor, allowing users to customize your component without writing code.Schema Structure
Common Input Types
-
Basic Inputs
text
: Single-line text inputtextarea
: Multi-line text inputrichtext
: Rich text editor with formattingnumber
: Numeric inputcolor
: Color pickertoggle
: Boolean switchselect
: Dropdown selectionrange
: Slider inputtoggle-group
: Group of exclusive options
-
Media Inputs
image
: Image selectorvideo
: Video selectorfile
: File selector
-
Layout Inputs
position
: Position selector (top/center/bottom, left/center/right)spacing
: Margin and padding controlsalignment
: Text alignment controls
-
Special Inputs
product
: Product selectorcollection
: Collection selectordatepicker
: Date and time selectorheading
: Section divider with heading
Input Configuration
Each input type has specific configuration options:Advanced Schema Example
Data Integration
In a Weaverse Hydrogen project, there are two distinct types of loader functions:- Remix Route Loaders: These loaders are used in Remix route files (
routes/*.tsx
) and follow the Remix conventions - Weaverse Component Loaders: These loaders are defined in Weaverse component files and enable server-side data fetching at the component level
Remix Route Loaders
In Remix route files, you define loaders that run on the server and provide data to all components rendered by that route:Weaverse Component Loaders
Weaverse components can define their own loaders, which fetch data specifically for that component. This allows for more modular and reusable components that bring their own data:Key Differences
-
Scope:
- Remix loaders provide data to an entire route
- Weaverse component loaders provide data only to the specific component
-
Access:
- Remix loader data is accessed via the
useLoaderData()
hook - Weaverse component loader data is received via
props.loaderData
- Remix loader data is accessed via the
-
Arguments:
- Remix loaders receive
{ params, request, context }
- Weaverse component loaders receive
{ weaverse, data, request }
where:weaverse
: Contains Weaverse-specific utilities and contextdata
: Contains the component’s configured data from the editorrequest
: The original request object
- Remix loaders receive
-
Use cases:
- Use Remix loaders for route-level data like page information
- Use Weaverse component loaders for component-specific data
Data Flow Between Components
Components can access data from their parent components using theuseParentInstance
hook:
Data Fetching Best Practices
- Type Safety: Always define proper TypeScript interfaces for your loader data:
- Error Handling: Implement proper error handling in your loaders:
- Data Transformation: Transform data in the loader before passing it to the component:
- Caching: Leverage Hydrogen’s built-in caching mechanisms and Weaverse’s utilities for improved performance:
fetchWithCache
is a convenient utility that simplifies cached data fetching from external APIs:
- Available through
context.weaverse.fetchWithCache
- Automatically handles JSON parsing
- Applies the specified caching strategy
- Provides a cleaner syntax compared to Hydrogen’s native
fetchSync
CacheNone()
: No caching, always fetches fresh dataCacheShort()
: Short-term caching (a few minutes)CacheLong()
: Long-term caching (1 day by default)cache.with()
: Custom cache control
Component Organization Patterns
1. Parent-Child Component Structure
2. Reusable Component Parts
Styling Patterns
1. CVA for Variant Management
2. CSS Custom Properties
Interactive Components
1. Countdown Timer
2. Hotspots
Best Practices
1. Using CVA with Select Inputs
Class Variance Authority (CVA) provides an elegant way to handle component variants that map directly to schema select inputs. This pattern creates a strong connection between your schema inputs and component styling:- Type Safety: CVA provides type checking for variant values
- Single Source of Truth: Variant options in schema match exact keys in CVA
- Maintainability: Changes to variant names only need to happen in one place
- Composition: Easily combine multiple variants for complex styling
- Default Values: Set defaults in CVA that match schema defaults
- Responsive Design: Apply responsive styles within variant definitions
2. Component Architecture
-
Use TypeScript for better type safety
- Define explicit prop interfaces
- Use generics for reusable components
- Utilize TypeScript’s utility types for prop manipulation
-
Follow React’s Best Practices
- Always use
forwardRef
for all components - Separate component logic from presentation
- Extract reusable UI elements into smaller components
- Use composition over inheritance
- Always use
-
Optimize Component Structure
- Keep components focused on a single responsibility
- Create dedicated files for types and utilities
- Use meaningful names for components and props
- Document complex logic with comments
3. State Management
4. Error Handling
5. Accessibility
- Follow WAI-ARIA Guidelines
- Use semantic HTML elements
- Add proper ARIA attributes
- Ensure keyboard navigation works
- Provide sufficient color contrast
6. Performance Considerations
- Memoize expensive calculations with
useMemo
- Optimize callback functions with
useCallback
- Use
React.memo
for components that render often but rarely change - Implement virtualization for long lists
- Lazy load components that aren’t immediately visible
Troubleshooting
Common Issues
-
Component not appearing in Studio
- Verify component registration in
components.ts
- Check schema type uniqueness across all components
- Ensure all required props are handled in the component
- Check for syntax errors in the component or schema
- Verify the component is exported correctly (both default export and schema)
- Verify component registration in
-
Schema not updating
- Clear browser cache and refresh the page
- Restart development server to reload all components
- Verify schema syntax is correct
- Check browser console for errors
- Ensure component and schema are properly exported
-
Data loading issues
- Check loader implementation for errors
- Verify data types match what’s expected
- Implement error boundaries to catch and display errors
- Add logging to debug data loading process
- Check network requests in browser DevTools
-
Styling issues
- Check for CSS conflicts with other components
- Verify class names are being applied correctly
- Inspect the DOM to see which styles are actually applied
- Test with inline styles to isolate CSS framework issues
- Check for responsive design breakpoints
Debugging Tips
Development Environment Setup
For effective debugging:- Enable React DevTools in your browser
- Use VS Code with TypeScript support for real-time type checking
- Configure ESLint with React and TypeScript rules
- Set up source maps for better debugging in development
- Use Chrome DevTools to inspect components and network requests
Next Steps
- Learn about Component Schema for advanced schema configuration
- Explore Data Fetching for more data integration patterns
- See Example Components for inspiration and reference implementations
- Join our Community for support and sharing best practices
Conclusion
Building Weaverse components requires understanding the interplay between React components, schema configuration, and data integration. By following the patterns and practices outlined in this guide, you can create powerful, customizable, and performant components that enhance your Hydrogen theme. Remember that great components are:- Reusable: They can be used in multiple contexts
- Customizable: They provide sensible defaults but allow for customization
- Accessible: They follow web accessibility guidelines
- Performant: They load quickly and render efficiently
- Maintainable: They follow clean code principles and are well-documented