Connect ViewModel to View
In the previous section, we created a ViewModel and a React component. Now we need to connect them together. We need import the hook function and the ViewModel instance into the React component, and then call the hook function to connect them.
HelloWorld.tsx
import React from 'react';
import {
  useHelloWorldViewModel,
  helloWorldViewModel,
} from './HelloWorld.viewModel';
function HelloWorld(props: any) {
  // Get ViewModel data
  const data = useHelloWorldViewModel();
  React.useEffect(() => {
    // init data
    helloWorldViewModel.init({
      name: 'Hello World',
    });
  }, []);
  function onClick() {
    // Call ViewModel method
    helloWorldViewModel.setIsClicked(true);
  }
  return (
    <div>
      <h1>Hello World</h1>
      <h2>isClicked: {data.isClicked ? 'true' : 'false'}</h2>
      <button onClick={onClick}>Click Me!</button>
    </div>
  );
}
export default HelloWorld;