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

How to create useMorph instances dynamically and share them (useMorphId?) #27

Closed
renatorib opened this issue Jul 25, 2019 · 1 comment
Closed

Comments

@renatorib
Copy link

renatorib commented Jul 25, 2019

I have a list of posts, and I have the post.
The list item is visually very similar to the post header and I'm trying to morph it.

But I have two problems here: I need to create morph 'instances' dynamically, somethink like id based, "on demand", and I need to share this instance to different files/components.

Something like this:

listing page:

const PostTeaser = ({ ...post }) => {
  const useMorphId(`post-${post.id}`)
  return <div {...morph}>...</div>
}

const PostList = ({ posts }) => (
  <div>{posts.map(post => <PostTeaser {...post} key={post.id} />)}</div>
)

post page:

const PostHeader = ({ ...post }) => {
  const useMorphId(`post-${post.id}`)
  return <div {...morph}>...</div>
}

const PostPage = ({ post }) => (
  <div>
    <PostHeader {...post} />
    <div>...</div>
  </div>
)

After many attempts and tested workarounds, I was able to do it using a Context that saves the instances by id in its state, and a hook that ask for a instance by id: if it doesn't exist, it creates, if it exists, it uses the existing one.

Code: https://codesandbox.io/s/nervous-mendeleev-ynrbq
(the magic is in morpher.js, and morphs are in pages/posts.js and pages/post.js)

But... questions:

  1. Is there an easier way to satisfy this use case?
  2. Is there a more trivial way to share instances without prop drilling or context?
@renatorib renatorib changed the title Dynamically create useMorph instances and share them (useMorphId?) How to create useMorph instances dynamically and share them (useMorphId?) Jul 25, 2019
@renatorib
Copy link
Author

renatorib commented Jul 25, 2019

Good news.
I was able to do it in a much simpler way, but I don't know if it would have negative impacts, for example performance.

https://codesandbox.io/s/cool-haze-4n8hi

Morphs are stored in a singleton

import { useMorph } from "react-morph";

const morphs = new Map();

export const useMorphId = id => {
  // can't wrap a hook in a if statement, so we create it here even if we don't use it
  const morph = useMorph();
  if (!morphs.has(id)) morphs.set(id, morph);
  return morphs.get(id);
};

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

1 participant