Add Angular/Vue-like Reactivity to React
import React from "react"
import { useViewModel } from 'use-view-model'
export class FooViewModel {
title = 'Foobar'
}
export const Foo = () => {
const vm = useViewModel(() => new FooViewModel())
return <div>
<div>{vm.title}</div>
<input
type="text"
value={vm.title}
onChange={e => vm.title = e.target.value} />
</div>
}
You can add methods to your view model
import React from "react"
import { useViewModel } from 'use-view-model'
export class BarViewModel {
title = 'Foobar'
reset() {
this.title = 'Foobar'
}
}
export const Bar = () => {
const vm = useViewModel(() => new BarViewModel())
return <div>
<div>{vm.title}</div>
<input
type="text"
value={vm.title}
onChange={e => vm.title = e.target.value} />
<button
onClick={() => vm.reset()}>
Reset
</button>
</div>
}
You can test view logic without being concerned about the DOM or browser. You can take also advantage of dependency injection.
import { BarViewModel } from './foo.tsx'
it('Should reset title when', () => {
const vm = new BarViewModel()
const startingValue = vm.title
vm.title = 'changed'
vm.reset()
expect(vm.title).toBe(startingValue)
})
To use this for Preact change the import path to
import { useViewModel } from 'use-view-model/preact'