Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for fetching non-node djedi content in djedi-react #113

Open
eliassjogreen opened this issue Nov 1, 2022 · 3 comments
Open

Support for fetching non-node djedi content in djedi-react #113

eliassjogreen opened this issue Nov 1, 2022 · 3 comments

Comments

@eliassjogreen
Copy link
Contributor

I have encountered several different situations where I would like to fetch get a simple string from djedi-react, without using the Node element. There might already be ways to do this but it does not seem like they are very well documented nor as easy to use as the good old <Node uri=""></Node> in react components. Usecases I have found for this is for example using a djedi value as the title or entry in a select dropdown, currently it is fetched but simply coerced into a [object Object] string.

@hbystrom91
Copy link

@eliassjogreen I usually have a helper component for this. You can do something like:

import React from 'react';

import { DjediNodeState, DjediNodeStateAlternate } from 'types/Djedi';

const getDjediNodeTextContent = (state: DjediNodeStateAlternate | DjediNodeState) =>
  typeof state.content === 'object' ? state.content.props.children : state.content;

interface RestProps {
  [key: string]: unknown;
}

interface DjediContentProps extends RestProps {
  node: React.ReactElement;
  children: (content: string) => React.ReactNode;
}

const DjediContent = ({ node, children, ...restProps }: DjediContentProps) => {
  return React.cloneElement(node, {
    ...restProps,
    render: function getElementState(state: DjediNodeStateAlternate | DjediNodeState) {
      return children(state.type === 'success' ? getDjediNodeTextContent(state) : '');
    },
  });
};

export default DjediContent;

And in your field components you would check the type of the prop. Either it would be a string or an object (if it's a node). If it's a node you wrap with DjediContent, otherwise you just pass the string.

@eliassjogreen
Copy link
Contributor Author

Ah ok, thanks! It feels like this should probably be part of djedi-react itself as it is a quite common issue I encounter, and the helper while nice feels a bit like an added layer of indirection.

@hbystrom91
Copy link

It could be a part of djedi-react for sure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants