When using MobX with React in environments that do not support decorator syntax, we can directly convert React components into reactive components using the observer function. This approach avoids decorator syntax entirely and instead employs a function wrapper. The main steps are as follows:
- Import necessary modules: First, import the
observerfunction from themobx-reactpackage.
javascriptimport { observer } from 'mobx-react';
- Create a React component: Define a standard React component.
javascriptimport React from 'react'; function TodoView({ todo }) { return ( <div> <input type="checkbox" checked={todo.finished} onChange={() => todo.toggle()} /> {todo.title} </div> ); }
- Use the
observerfunction: Wrap your React component with theobserverfunction to make it reactive. This ensures the component automatically re-renders when observed data changes.
javascriptconst ObservableTodoView = observer(TodoView);
- Use the component: Integrate the converted component into your application.
javascriptimport ReactDOM from 'react-dom'; import { observable } from 'mobx'; const todo = observable({ title: "Learn MobX", finished: false, toggle() { this.finished = !this.finished; } }); ReactDOM.render(<ObservableTodoView todo={todo} />, document.getElementById('app'));
In the above example, the TodoView component is converted into a MobX reactive component via the observer function. Consequently, when the finished property of the todo object changes, the TodoView component automatically re-renders to reflect the updated state.
This approach is straightforward and applicable to JavaScript environments without decorator support, such as the default configuration of Create React App. It not only maintains code clarity and manageability but also leverages MobX's reactive programming benefits.