Melody Documentation
  • Why Melody?
  • Quickstart
    • What is Melody?
    • Tutorial
    • Installation
  • Templates
    • Twig
    • Mounting Components
    • Keys and Loops
    • Attributes
    • CSS Classes
    • Inline Styles
    • Refs
    • CSS Modules
  • Melody-Streams
    • Basic concept
    • A Step-by-Step Walkthrough
  • MELODY-STREAMS API
    • createComponent
    • The component function
  • melody-hooks
    • Overview
    • Rules of Hooks
    • Event Handling
    • Separation of Concerns
  • melody-hooks API
    • useState
    • useAtom
    • useEffect
    • useRef
    • useCallback
    • useMemo
    • useReducer
    • usePrevious
  • melody-component
    • Overview
  • melody-hoc
    • Overview
Powered by GitBook
On this page
  • Description
  • Usage
  • Partial application

Was this helpful?

  1. MELODY-STREAMS API

createComponent

Description

The createComponent function is used merge a component function and a template into a Melody Component. The component function must match the melody-streams API.

Usage

import { createComponent } from 'melody-streams';
import ButtonTemplate from './Button.twig';

function Button({ props }) {
    return props;
}

export default createComponent(Button, ButtonTemplate);

Partial application

Instead of directly providing both the component function and the template, it is possible to create a component in two steps by first providing the component function and then applying the returned function to a template.

This is particularly useful when you would like to conditionally enable a different UI for a component, for example because you're running an A/B test.

import { createComponent } from 'melody-streams';
import BlueButton from './BlueButton.twig';
import RedButton from './RedButton.twig';
import { hasTreatment } from '@mycomp/experiments';

function Button({ props }) {
    return props;
}

const ButtonLike = createComponent(Button);
const Button = hasTreatment('red-button') ? ButtonLike(RedButton) : ButtonLike(BlueButton);

export default Button;

This approach can also be useful when different components share the same behaviour. For example, a Checkbox and a ToggleButton might look very different but their behaviour is almost identical when it comes to state (can be toggled, has a selected state, etc.).

PreviousA Step-by-Step WalkthroughNextThe component function

Last updated 5 years ago

Was this helpful?