Steven
Steven

Reputation: 1700

Adding items to Android React Native Developer menu

In React Native when making development builds you can shake the device or use the menu button to bring up a developer menu. How do you add an additional custom item to this menu? I haven't been able to find any documentation on adding another item but I think it would be very handy to say toggle between server environments (dev, prod, etc.) from the dev menu rather than making separate builds to test against each environment.

Upvotes: 8

Views: 2516

Answers (2)

Sanjeev
Sanjeev

Reputation: 4375

You can use DevSettings addMenuItem function to add item in React Native developer menu

in your main App.js component, write

import { DevSettings } from 'react-native';

//...

useEffect(() => {
    // componentDidMount

    // Add our toggle command to the menu
    DevSettings.addMenuItem('Toggle Storybook', () => {
        // Perform your logic here
    });
}, []);

Upvotes: 8

Petter Hesselberg
Petter Hesselberg

Reputation: 5498

The DevSupportManager class can do this for you. You can get it from your ReactNativeHost instance via its ReactInstanceManager:

ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
DevSupportManager devSupportManager = reactInstanceManager.getDevSupportManager();

With that in hand, add a custom dev option as follows:

devSupportManager.addCustomDevOption("Custom dev option", new DevOptionHandler() {
    @Override
    public void onOptionSelected() {
        Toast.makeText(MainActivity.this, "Hello from custom dev option", Toast.LENGTH_SHORT).show();
    }
});

Where you get hold of your ReactNativeHost instance in the first place depends on how you've structured your app. If you created the app using react-native init, your main application class will include this:

@Override
public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
}

...which you could call.

I have a complete sample here; look at MainActivity.OnCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MainApplication application = (MainApplication) getApplication();
    ReactNativeHost reactNativeHost = application.getReactNativeHost();
    ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
    DevSupportManager devSupportManager = reactInstanceManager.getDevSupportManager();
    devSupportManager.addCustomDevOption("Custom dev option", new DevOptionHandler() {
        @Override
        public void onOptionSelected() {
            Toast.makeText(MainActivity.this, "Hello from custom dev option", Toast.LENGTH_SHORT).show();
        }
    });
}

Upvotes: 2

Related Questions