Skip to content

sinoon/reactivue

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

4 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

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?

Install

npm i reactivue @vue/runtime-core react react-dom

Usage

It's currently expiremental and might have some breaking changes in the future. No production yet but feel free to try it out.

Factory

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)

Hooks

You can use it as a hook as well.

The define factory 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>
  )
}

Example

Check packages/example

License

MIT - Anthony Fu 2020

About

๐Ÿ™Š Use Vue Composition API in React components

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 79.6%
  • HTML 13.8%
  • JavaScript 6.6%