Last active
June 22, 2019 20:17
-
-
Save bnjm/04e7d8a5daec7c4b69e01d3ea01ef0a9 to your computer and use it in GitHub Desktop.
Render Vue components in React 🤪
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// What: Render a Vue component in React | |
// How: Returns a wrapped Vue component which can be rendered as a React component | |
// When to use this? Almost certainly, never | |
// Example usage: https://codesandbox.io/s/usevuecomponentexample-tmmln | |
import Vue from 'vue' | |
import React, { useRef, useEffect, useCallback } from 'react' | |
const getWrappedVueComponent = component => props => { | |
const container = useRef() | |
const instance = useRef() | |
useEffect(() => { | |
instance.current = new Vue({ ...component, el: container.current }) | |
}, []) | |
useEffect(() => { | |
// Object.assign will trigger the instance setters and update the component | |
Object.assign(instance.current, props) | |
}, [props]) | |
return <div ref={container} /> | |
} | |
const useVueComponent = component => { | |
// useCallback should prevent returning a new component type each render | |
return useCallback(getWrappedVueComponent(component), []) | |
} | |
export { useVueComponent, getWrappedVueComponent } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: https://codesandbox.io/s/usevuecomponentexample-tmmln