ProAI / extended-components

:star2: React.js functional components with default props, advanced local state and lifecycle hooks
MIT License
1 stars 1 forks source link

Proposal for v0.2.0 #1

Open markusjwetzel opened 6 years ago

markusjwetzel commented 6 years ago
import {
  createState,
  extended,
  statics,
  defaultProps,
  params,
  lifecycle,
  pure
} from 'react-envelope';

const createToggleState = (initialOn = false) => ({
  const initial = {
    on: initialOn,
  };
  const mutators = setState => ({
    toggle: () => {
      setState(({ on }) => ({ on: !on })),
    }
  });

  // `createState` will create a component with a render prop that might be used with
  // `parameters` hoc, too.
  return createState(initial, mutators);
});

const ToggleState = createToggleState();

// These functions are not hoc's. They will pass through a `ComponentBag` that will be formed
// to a component inside the `extend` function.
const extensions = [
  statics({
    ComponentItem,
  }),
  defaultProps({
    ...
  }),
  // Declare additional function parameters, use any render prop component.
  params(ToggleState, ThemeContext, DeviceMotion, ...),
  // Use render prop components with lifecycles!
  lifecycle((props, toggle, theme, motion, ...) => ({
    componentDidMount() {
      ...
    }
  })),
  pure(),
];

// Use declared parameters with Component
function Component(props, toggle, theme, motion, ...) {
  ...
}

export default extended(Component, extensions);
markusjwetzel commented 6 years ago
// In case of lifecycles AND render prop components, we will need a WrapperComponent.
function OuterComponent() {
  return (
    <Composer components={[]}>
      {([resultOne, resultTwo, resultThree]) => (
        <InnerComponent __results={{ resultOne, resultTwo, resultThree }} />
      )}
    </Composer>
  );
}
markusjwetzel commented 6 years ago

Another option might be a plugin system like the webpack one:

const extensions = [
  new plugins.Statics({
    ComponentItem,
  }),
  new plugins.DefaultProps({
    ...
  }),
  new plugins.State(ToggleState),
  new plugins.RenderProp(ThemeContext, DeviceMotion),
  new plugins.Lifecycle((props, toggle, theme, motion, ...) => ({
    componentDidMount() {
      ...
    }
  })),
  new plugins.Pure(),
];