use redux-devtools-extension with react-native with chrome - react-native

Need help in setup Redux devTools for react-native
I have very simple reducer and createStore here, and I try to incorporate redux-devtools-extension, so I can debug my react-native
app, but I got "store no found" in Redux tab
import { createStore, applyMiddleware} from 'redux'
import {reducer} from "./reducers"
import { composeWithDevTools, devToolsEnhancer } from 'redux-devtools-
extension'
let store = createStore(reducer, devToolsEnhancer());
export const reducer = (state=[], action) => {
switch(action.type) {
case "ADD_MEMBER":
return [...state, {categoryID: 0, name: "Bill", zip: "27733", id: 4}]
default:
return state
}
return state;
}

Redux DevTools Extension cannot access the React Native worker, as extensions cannot inject code into web workers. You have to use remote-redux-devtools to communicate with the extension via websockets.
You'll have just to replace
import { devToolsEnhancer } from 'redux-devtools-extension'
with
import devToolsEnhancer from 'remote-redux-devtools';
Then from the extension context menu, click on "Open Remote DevTools". By default it'll use its remote server for quick bootstrapping, but it's recommended to run your local server by installing and running remotedev-server. It's similar to how you have to install and run react-devtools package for React Native.

Another option is to use React Native Debugger.
The win is, you don't have to npm install redux devtools every time. The debugger provides you the good old "REDUX_DEVTOOLS_EXTENSION" out of the box.
So, if you are reusing code from web, you do not need any code changes. The same set up as redux devtools extension will just work.
For a thorough guide on how to setup React Native Debugger with an Expo app look here. (As the official docs are a bit confusing.)

Related

React Native Storybooks Component not Loading

I'm trying to load the default stories that come when you first install Storybook. Had some issues getting the server to start but I managed to fix it by adding port and host in the config. But even after getting it to run, clicking on any of the components doesn't update.
I'm expecting to see a Button.
And ideas? Here's the storybook index.js. I'm using Expo.
// if you use expo remove this line
// import { AppRegistry } from "react-native";
import {
getStorybookUI,
configure,
addDecorator,
} from "#storybook/react-native";
// import { withKnobs } from '#storybook/addon-knobs';
import "./rn-addons";
// enables knobs for all stories
// addDecorator(withKnobs);
// import stories
configure(() => {
require("./stories");
}, module);
const StorybookUIRoot = getStorybookUI({
host: "192.168.100.6", // replace this ip address with your local ip address
port: "7007",
asyncStorage: null,
});
// If you are using React Native vanilla and after installation you don't see your app name here, write it manually.
// If you use Expo you should remove this line.
// AppRegistry.registerComponent("%APP_NAME%", () => StorybookUIRoot);
export default StorybookUIRoot;
Also not sure if this is related but I've had to comment out addon-knobs in addons.js because it can't find it even though I have addon-knobs in my package.json:
import '#storybook/addon-actions/manager';
import '#storybook/addon-links/manager';
// import '#storybook/addon-knobs/manager';
I've tried replacing it with
register
like I've read on here but it still didn't work.
import '#storybook/addon-knobs/register';

remote redux devtools stopped working

This question has been asked before but I cannot find a working solution so I'm taking the liberty to show my code in case I am missing something. I have a react native app and using redux. I have been using remote-redux-devtools for two months on this project now, but the tool stopped working all of a sudden. I receive a "SocketProtocolError" in the console and will paste that below as well as my code.
Redux store
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "remote-redux-devtools";
import thunk from "redux-thunk";
import reducers from "../../State/reducers/index";
const composeEnhancers = composeWithDevTools({ realtime: true });
const store = createStore(
reducers,
{},
composeEnhancers(applyMiddleware(thunk))
);
export default store;
In my package.json file I am using "remote-redux-devtools": "^0.5.13"
This is the error I get in the console.
Any help would be greatly appreciated!
I fixed the same error when debugging an app on my phone by running:
adb reverse tcp:5678 tcp:5678
to allow the phone to connect to the devtools. Adjust the port number if using a different one. If you're running the app in an emulator on your computer, this probably won't help.

How To Use both 'adjustPan' and 'adjustResize' for 'windowSoftInputMode' in React Native Android app

How can I use both 'adjustPan' and 'adjustResize' in AndroidManifest.xml react native app.
Use Case
My navigation is made upon ReactNavigation with StackNavigator and TabNavigator. I have a text box where the user can type any data. While performing this, the tab bar is displaying on the top of Keyboard. In order to block this i used 'adjustPan' and it worked fine.
On another screen, I have a registration with multiple text boxes. Here I cant scroll the entire screen unless and clicking 'tick' on the keyboard or manually click system back button. To solve this issue I found 'KeyboardAvoidingView' which is working fine. but to activate this need to change 'windowSoftInputMode' to 'adjustResize'.
In documentation, found that these two have entirely different property and I can't both together. could someone help me on this?
References:https://medium.freecodecamp.org/how-to-make-your-react-native-app-respond-gracefully-when-the-keyboard-pops-up-7442c1535580
I found an npm package called react-native-android-keyboard-adjust, which allows us to switch the windowSoftInputMode on demand, this should be able to cater for your use case. However, the library seems to be not actively maintained and the installation documentation is a little bit out of date but for the most part, you can follow the instructions given by the README.md.
For the Update MainActivity.java in your project part, the recent versions of React Native should be able to auto-link the dependencies and there is no need to do this modification manually.
After the above steps, you can try to start your app. If you encountered an error related to something like The number of method references in a .dex file cannot exceed 64k, you can add the followings to your android/app/build.gradle file
android {
...
defaultConfig {
...
multiDexEnabled true
}
...
}
After installing the package, you can call the methods provided by the library to change the windowSoftInputMode as you need.
For example, assuming you have a default windowSoftInputMode of adjustResize, and you want to use adjustPan within ScreenA, you can call AndroidKeyboardAdjust.setAdjustPan() when ScreenA mount, and reset the windowSoftInputMode to adjustResize on unmount by calling AndroidKeyboardAdjust.setAdjustResize()
As of 2023, the best choice is react-native-avoid-softinput. react-native-android-keyboard-adjust isn't supported anymore.
You can use AvoidSoftInput.setAdjustPan and AvoidSoftInput.setAdjustResize.
I use custom hook to disable my default behavior on some screens.
import { useCallback } from 'react'
import { AvoidSoftInput } from 'react-native-avoid-softinput'
import { useFocusEffect } from '#react-navigation/native'
import { Platform } from 'react-native'
function useAndroidKeyboardAdjustNothing() {
useFocusEffect(
useCallback(() => {
if (Platform.OS === 'android') {
AvoidSoftInput.setAdjustNothing()
AvoidSoftInput.setEnabled(true)
}
return () => {
if (Platform.OS === 'android') {
AvoidSoftInput.setEnabled(false)
AvoidSoftInput.setAdjustResize()
}
}
}, []),
)
}

setRootController error using react-native-navigation in Expo

I keep running into undefined is not an object (evaluating 'RCCManager.setRootController') when trying to use react-native-navigation.
I tried to follow suit with https://github.com/junedomingo/movieapp but hit this when it tries to load the project in the Expo app.
I've modified my App.js generated by Expo to look like this:
import HomeScreen from './screens/HomeScreen'
Navigation.registerComponent('screens.HomeScreen', () => HomeScreen)
class App extends React.Component {
constructor(props) {
super(props)
this.startApp()
}
startApp() {
Navigation.startTabBasedApp({
tabs: [
{
label: 'One',
screen: 'screens.HomeScreen',
title: 'Screen One'
},
]
})
}
}
const app = new App()
That's a bit boiled down, but I think those are the essential bits. I feel like I'm not handing things off from rnn to Expo the way Expo is expecting.
Any idea how to get rnn running in Expo? If there's an example repo I can play with, that would be great. I'm sure I can get rnn working outside Expo, so vanilla rnn examples probably won't help much.
Because react-native-navigation has native dependencies and need you to add custom native code you can not use it with Expo out of the package.
One option is to detach your project and use the package like that. This has a side effect of loosing some expo properties.
Another option is (if you are not too deep in the project) creating a new app with react-native-cli and moving your code to that project. This has side effect of not being able to use expo api.
Third option is to use a navigation package that doesn't depend on native code. Some of the most popular options are react-navigation and react-native-router-flux.

How to use enzyme for react-native with jest

I have followed –or tried to– several posts on how to do it, including the airbnb enzyme's guide for (separatedly) react-native and jest. (E.g: https://medium.com/#childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt, https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5 or How to use Jest with React Native)
But I keep getting lots of warnings (I have multiple set of concurrent tests) whenever I try to render (not mount, it crashes) any native component. Warnings are always about a native prop not being recognised.
Warning: Unknown props `focus`, `secureTextEntry` on <TextInput> tag. Remove these props from the element.
in TextInput (created by TextInput)
in TextInput (created by PasswordInput)
Anyone who has a set up working, recognises how to remove the warning or how to solve it?
Thanks
So I know this is a bit old but I was having issues with Jest, Enzyme, and React Native and I found this post - hopefully this solution will help.
To start with - Enzyme doesn't support mounting React Native and only supports shallow rendering. This wasn't good enough for me as I needed end-to-end tests from the component to the api which lead me to react-native-mock-render. What this does is allow us to run react native inside a browser environment which let's us test using Enzyme - all the calls for React Native and the components work as you would expect.
To set this up you'll need to install JSDOM, react-native-mock-render, Enzyme 3.0+, and Jest 20.0.0+. And then inside your jest setup file (which is specified in your package.json) include the following code:
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM();
const { window } = jsdom;
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
// Setup adapter to work with enzyme 3.2.0
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
// Ignore React Web errors when using React Native
console.error = (message) => {
return message;
};
require('react-native-mock-render/mock');
And that's it - you're all setup to mount components in Enzyme and test them.
If you want to see a full sample check out react-native-mock-render-example. This is working with React 16, React Native 0.51, and Enzyme 3.2.
In order to unit test your component with jest you can use enzyme-to-json
npm install --save enzyme-to-json
then your test would look like this:
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import MyComponent from './MyComponent';
it('should render component', => {
expect(shallowToJson(shallow(<MyComponent />))).toMatchSnapshot();
});
I'm not sure regarding your case with react-native.
I can share my case of using jest + enzyme with standard react.
When I needed to test some component and isolate it from others I used jest.mock, e.g.
jest.mock('../ComponentToBeMocked', () => {
return () => null;
});
Initially I found examples when the second argument (a function) should return just a string representing a name of the mocked component. But in that case I saw that distracting Unknown props warning.