Use Vue Composition API in React components
{WIP}
I love Vue Composition API and it's reactivity system,
but functional components in React are also sweet with Typescript support.
So, why not to use them together?
npm i reactivue @vue/runtime-core react react-dom
It's currently expiremental and might have some breaking changes in the future. No production yet but feel free to try it out.
import React from 'React'
import { ref, computed } from '@vue/runtime-core'
import { define } from 'reactivue'
interface Props {
value: number
}
const MyCounter = define(
// setup function in Vue
(props: Props) => {
const counter = ref(props.value)
const doubled = computed(() => counter.value * 2)
const inc = () => counter.value += 1
return { counter, doubled, inc }
},
// functional component in React
({ counter, doubled, inc }) => {
// you can still use other React hooks
return (
<div>
<div>{counter} x 2 = {doubled}</div>
<button>Increase</button>
</div>
)
}
)
// use it as you normally would
render(<MyCounter value={10}>, el)You can use it as a hook as well.
The
definefactory is actually a sugar to make the following code simplier.
import React from 'React'
import { ref, computed } from '@vue/runtime-core'
import { useVue } from 'reactivue'
interface Props {
value: number
}
function MyCounter(Props: Props) {
const state = useVue(
(props: Props) => {
const counter = ref(props.value)
const doubled = computed(() => counter.value * 2)
const inc = () => counter.value += 1
return { counter, doubled, inc }
},
Props // pass React props to it
)
// state is a plain object just like React state
const { counter, doubled, inc } = state
return (
<div>
<div>{counter} x 2 = {doubled}</div>
<button>Increase</button>
</div>
)
}Check packages/example
MIT - Anthony Fu 2020