Skip to content

Instantly share code, notes, and snippets.

@darklight721
Last active December 7, 2020 12:57
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save darklight721/f3e94e77d88b3c89fcba0affd2fb95fa to your computer and use it in GitHub Desktop.
Save darklight721/f3e94e77d88b3c89fcba0affd2fb95fa to your computer and use it in GitHub Desktop.
Using MobX with decorators in React Native

Using MobX with decorators in React Native

The following instructions should work with React Native v0.32:

  1. Install mobx libraries.

    npm install mobx --save
    npm install mobx-react --save
  2. Install babel plugins to enable decorators.

    npm install babel-preset-react-native --save-dev
    npm install babel-plugin-transform-decorators-legacy --save-dev
  3. Create a .babelrc file.

    {
     "presets": ["react-native"],
     "plugins": ["transform-decorators-legacy"]
    }
  4. Done! Now you can write components like:

    import React, { Component } from 'react'
    import { TextInput } from 'react-native'
    import { action } from 'mobx'
    import { inject, observer } from 'mobx-react/native'
    
    @inject('store') @observer
    export default class CommentBox extends Component {
      render() {
        return <TextInput value={this.props.store.comment} onChangeText={this.handleChange} />
      }
      
      @action
      handleChange = value => this.props.store.comment = value
    }
@eduardojunio
Copy link

It doesn't work, I'm getting this error: Support for the experimental syntax 'decorators-legacy' isn't currently enabled
Myreact-native version is 0.56.0

@fernandopascoalbr
Copy link

It doesn't work, I'm getting this error: Support for the experimental syntax 'decorators-legacy' isn't currently enabled
Myreact-native version is 0.56.0

It work for me ~> https://stackoverflow.com/questions/52758721/how-to-use-mobx-with-decorators-in-react-native-0-57

@avatari1
Copy link

avatari1 commented Jul 17, 2019

actually u need mobx-react@5 specifically which is known to work and also your babel.config.js to look like this

module.exports = function(api) {
api.cache(true);
   return {
      presets: ['babel-preset-expo'],
      "plugins": [
         [
            "@babel/plugin-proposal-decorators",
            {
               "legacy": true

            }
         ]
      ]
   
   };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment