0

Lets say I have four components and I want to conditionally render them depending on a type prop using daggy:

In this example type prop value can be the string a, b, c or d

here is a working codesandbox example

import daggy from 'daggy';
import { componentA, componentB, componentC, componentD } from './components';

const UI = daggy.taggedSum('UI', {
  A: [],
  B: [],
  C: [],
  D: [],
});

const VIEWS = {
  a: UI.A,
  b: UI.B,
  c: UI.C,
  d: UI.D,
};

const getView = (type) => VIEWS[type];

export const Component = ({ type }) => {
  const view = getView(type);
  return view.cata({
    A: () => <ComponentA />,
    B: () => <ComponentB />,
    C: () => <ComponentC />,
    D: () => <ComponentD />,
  });
};

This works as expected, but it seems a little bit complicated and I feel like I'm missing something here, I've read the documentation but I could not really understand how to apply it to this simple example.

The examples I found on internet are too complex for what I want to achieve, which is just rendering a component using daggy depending on a prop.

Here is an example of conditional rendering using daggy, unfortunately it uses an additional library to achieve this and it seems more complex than my example.

If there is an alternative way to achieve conditional rendering in a similar fashion without using daggy it would also solve my problem.

Any suggestions?

rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • What exactly is it you'd like to accomplish with daggy and React? – mzedeler Apr 23 '21 at 22:27
  • I would like to conditionally render a component using daggy and React, so given a prop value it would render one component or another. – rfc1484 Apr 23 '21 at 22:31
  • But it doesn't look like daggy is very helpful here. As far as you can see, you need something similar to an enumeration (think use A, B, C or D), but that doesn't seem to be something daggy has explicit support for. – mzedeler Apr 23 '21 at 22:35

1 Answers1

1

You don't need to use daggy at all! You only need to map each component with type and render it.

Try this:

import * as React from "react";

import { ComponentA } from "./ComponentA";
import { ComponentB } from "./ComponentB";
import { ComponentC } from "./ComponentC";
import { ComponentD } from "./ComponentD";

type ComponentProps = {
 type: string;
};

const componentVariants = {
  a: ComponentA,
  b: ComponentB,
  c: ComponentC,
  d: ComponentD
};


export const Component = ({ type, ...other }: ComponentProps) => {
  const Component = componentVariants[type];
  return <Component {...other} />;
};