Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all 6578 articles
Browse latest View live

How to webpack a node_module for use in both React and ReactNative

$
0
0

I'm building out a library that will be used by both a React Native project and a React project as a node_module hosted on my github.

This is proving quite daunting- and based on how ugly my code has become, I feel I must be doing something wrong.

Here's the presenting problem, the most recent issue:

Failed to compile.

./node_modules/plenti-api/src/services/AccountService.ts 11:10
Module parse failed: Unexpected token (11:10)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| export default class AccountService {
>   private client: IClient
|   constructor(client: IClient) {
|     this.client = client

This is occurring when trying to build the React project via npm start. The project successfully builds and runs on the React Native side of things.

what do I need to put in my .tsconfig / .webpack.config.js / somethingelse in order to allow for these typescript structures to exist in my library and be imported correctly into my web project?


Nested Tab Bar in stack with modal screen (React Navigation v5)

$
0
0

I am new to react native + js + ts so i have a big trouble righ now how to implement my navigation right.
am using react-navigation v5 right now.I have Tab navigator with 3 screens 'Home', 'Discover', 'Profile'. I need to make navigation that way i could present modal screen complitely on top of tab navigator. But reading docs i didn;t found how to do it from Tab navigator. So i deside to nest Tab navigator inside Stack navigator. And now i have tons of issues i need to resolve: 1. How i can show header for each tab in Tab navigator nested inside stack. 2. Show modal screen from view inside 'Home'. 3. Since i am using typescript before v5 i was using v4 with NavigationInjectedProps. i could access fron nested component inside 'Home' with no problems, but now i having undefined props.navigate / props.navigation

MainNavigator.tsx

import HomeScreen from './Home/HomeScreen';
import DiscoverScreen from './Discover/DiscoverScreen';
import ProfileScreen from './profile/ProfileScreen';
import StreamsTabScreen from './Discover/tabview/tabScreens/StreamsTabScreen';
import { Image, Platform, View } from 'react-native';
import React from 'react';
import images from 'assets/images'
import DeviceInfo from 'react-native-device-info';
import VideoPlayer from '../../library/ui/videoPlayer/VideoPlayer';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

export type TabNavigationProp = {
    Home: undefined;            //
    Discover: undefined;        // Should be here all undefined ????
    Profile: undefined;         //
}

export type StacknavigationProp = {
    TabNavigator: undefined;      // Same here ???
    ModalPlayer: undefined;       //
}


const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();


const TabNavigator = () => {
    return (
        <Tab.Navigator>
            <Tab.Screen name='Home' component={HomeScreen}  />
            <Tab.Screen name='Discover' component={DiscoverScreen} />
            <Tab.Screen name='Profile' component={ProfileScreen} />
        </Tab.Navigator>
    );
};


const MainStackNavigator = () => {
    return (
        <Stack.Navigator mode='modal'>
            <Stack.Screen name='TabNavigator' component={TabNavigator} options={{ headerShown: false }} />
            <Stack.Screen name='ModalPlayer' component={VideoPlayer} />
        </Stack.Navigator>
    );
}

export default MainStackNavigator;

HomeScreen.tsx

import { View, Text, StyleSheet, ScrollView } from "react-native";
import React from "react";
import StreamsScreen from '../../streamsScreen/StreamsScreen';
import VideoplayerScreen from '../../videoplayer/VideoplayerScreen';

import { CompositeNavigationProp } from '@react-navigation/native';
import { BottomTabNavigationProp } from '@react-navigation/bottom-tabs';
import { StackNavigationProp } from '@react-navigation/stack';
import { TabNavigationProp, StacknavigationProp } from "../MainNavigator";

export type HomeScreenNavigationProps = CompositeNavigationProp<
  BottomTabNavigationProp<TabNavigationProp, 'Home'>,
  StackNavigationProp<StacknavigationProp>
  >; //           made props type from docs guide...

export default class HomeScreen extends React.Component<HomeScreenNavigationProps> {
  render() {
    console.log(this.props.navigate); //navigate is undefined... 
    return (
      <View style={styles.container}>
        <ScrollView style={styles.scrollView}>
          <View style={{ paddingBottom: 24 }}>
            <StreamsScreen navigate={this.props.navigation} />   //props.navigation does not exist
            <View style={styles.separator} ></View>
            <VideoplayerScreen />
          </View>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
    backgroundColor: '#0C2B33',
    paddingBottom: 20,
  },
  separator: {
    height: 1,
    backgroundColor: '#3D908E'
  }
});

StreamsScreen.tsx

import { View, Text, StyleSheet, Image, ActivityIndicator } from 'react-native';
import MainViewItem from '../../library/ui/MainViewItem';
import { NavigationState, SceneRendererProps, TabBar, SceneMap } from 'react-native-tab-view';
import images from 'assets/images';
import { Props as IndicatorProps } from '../../library/indicator/TabBarIndicator';
import { fetchStreamsPending, fetchStreamsRefresh } from '../../redux/actions/streamActions';
import { connect } from "react-redux";
import { RootState } from "src/redux/reducers";
import numberFormatter from "../../library/utils/numberFormatter";
import palette from 'assets/palette';
import getLanguage from '../../library/utils/isoLanguages';

import {
    StreamsState,
    StreamsPendingState,
    StreamsErrorState,
    StreamsPageOffsetState,
    Stream,
    StreamsRefreshState
} from '../../redux/store/types';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { HomeScreenNavigationProps } from '../main/Home/HomeScreen';


interface StreamsProps {
    fetchStreamsPending: typeof fetchStreamsPending;
    fetchStreamsRefresh: typeof fetchStreamsRefresh;
    streams: StreamsState
    pending: StreamsPendingState;
    error: StreamsErrorState;
    pageOffset: StreamsPageOffsetState;
    refresh: StreamsRefreshState;
}


type State = NavigationState<{
    key: string;
}>;

type Route = {
    key: string;
};

class StreamsScreen extends React.Component<StreamsProps & HomeScreenNavigationProps> { // HomeScreenNavigationProps not sure what right prop type i need here ....

...
    _onPressCard = () => {
        this.props.navigation.navigate('ModalPlayer'); //Property 'navigation' does not exist on type ...
        this.props.navigate('ModalPlayer'); //undefined here
    }
...

Styling output of Object in Typescript react

$
0
0

I have an object output that looks like this:

name: "James Charles"
address: "<font face="Arial" size="2">10109 New York. Ste. C, New York NY</font>"
phone: "784-247-7926"
email: "jamescharles@yahoo.com"

I'm doing this in my render():

<ul>
    {(Object as any).entries(this.state.DocList).map((object, i) => <li>{object}</li>)}
</ul>

However, the output is displaying something like this:

nameJames Charles
address<font face="Arial" size="2">10109 New York. Ste. C, New York NY</font>
phone784-247-7926
emailjamescharles@yahoo.com

I'm trying to style up the output to add for example a space between the key and value, a semi colon, maybe a span class so I can bold the key fields.

How can I get more control of the output? And what would be the best way to strip the html from the address field so it's not displaying it in the address?

So that my output looks similar to this:

  • Name: James Charles
  • Address: 10109 New York. Ste. C, New York NY
  • Phone: 784-247-7926
  • Email: jamescharles@yahoo.com

How to set up node module to export type information

$
0
0

I'm writing a node module that is the api layer for my react and react native app. I've gotten it to the point where typescript is exporting everything except for the type objects. As I understand it, I could create a custom typing for my project, but that seems unnecessary. Here's what my compiled index.d.ts file looks like

import InventoryService from "./src/services/InventoryService";
import PlentiItemService from "./src/services/PlentiItemService";
...
declare type PlentiType = "Fruit" | "Decorative" | "Herb" | "Poultry" | "Vegetable" | "Unknown";
declare type QuantityName = "None" | "A Little" | "Some" | "A Lot" | "Many";
export { AccountLoginForm, AccountSignupForm, AccountUpdateForm, ..., PlentiType, QuantityName}

Note that the types are exported, but the don't appear to be usable in the installing application. Why is that?

How to test void functions using jest

$
0
0

I have a function that returns nothing. How can we write the jest test cases to verify this function?

onSilentTrackReadyToPlay(callback: (trackState: string) => void): void {
    this.trackReadySubscription = this.MediaPlayerEventEmitter.addListener(
      'silentTrackReadyToPlay',
      (trackState) => {
        if (callback) {
          callback(trackState)
        }
      },
    )
  }

When I save the code on VS code editor, auto change code format

$
0
0

I am coding on React Native. I downloaded the code from Git I will share my code Before saving enter image description here

After saving enter image description here

I already uninstalled all extensions Please help me Thanks

Custom Alert in React Native / typescript

$
0
0

I need to create a custom alert in React Native, using typeScript. I have to customize the titles and buttons, but I'm not getting it.

what is the difference between AsyncStorage and OnSaveInstanceState android


How to create typings alias in typescript the way we create dependency alias in babelrc?

$
0
0

TL;DR:

How to create typing alias in typescript the way we create dependency alias in babelrc?

The full question:

Let's say I am developing for iOS and web, and would like to write only one set of code. I am using React-Native and something that has an interface that is very similar to React-Native, for the sake of this question, let's call it Respond-Native(a made-up name).

In the project, I used a component called <Picker />. The Picker on Respond-Native(still the made-up library) has a property that is not present in React-Native called onSwipe.

But other than that, the rest of the interface is pretty much the same. Minute differences like this are all over Respond-Native.

And to make typing easier, I have two almost identical projects. The only thing that is different is that I added an alias to the .babelrc of the project that uses Respond-Native:

// .babelrc

{
  ...
  "plugins": [
    ...
    ["module-resolver", {
      "root": ["./"],
      "alias": {

        // the alias is here
        "react-native": "respond-native"

      }
    }]
  ]
}

However, when I write <Picker onChange={handleOnChange} onSwipe={handleOnSwipe} />, the editor does not know about the dependency alias and have no idea where the prop onSwipe comes from.

Sorry for the long build-up.

My question is, how can I do the same in creating typing alias (like I did in babelrc) so that VS Code would know which type declaration to use when checking types? (given that Respond-Native also has a Picker type/interface declared)

Cannot invoke an object which is possibly 'undefined'. using lodash.memoize

$
0
0

I'm using an example from react-native-localize and I want to support Typescript but I'm getting this error from line 36 translate.cache.clear(); the code works but I don't know how to convert memoize to a valid type, I'm new to this stuff, I have lodash.memoize types installed too, and the only way that I can remove this error right now is disabling strict mode in the tsconfig.json, can anyone help me please?

import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
import memoize from 'lodash.memoize';
import {I18nManager} from 'react-native';

type RequireFunction = {
  (): object;
};

interface TranslationGetters {
  [key: string]: RequireFunction;
}
[];

export const translationGetters: TranslationGetters = {
  // lazy requires (metro bundler does not support symlinks)
  en: () => require('../../locales/en.json'),
  es: () => require('../../locales/es.json'),
};

export const translate = memoize(
  (key: string) => i18n.t(key),
  // (key, config) => i18n.t(key, config),
  // (key, config) => (config ? key + JSON.stringify(config) : key),
);

export const setI18nConfig = () => {
  // fallback if no available language fits
  const fallback = {languageTag: 'en', isRTL: false};

  const {languageTag, isRTL} =
    RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
    fallback;

  // clear translation cache
  translate.cache.clear();
  // update layout direction
  I18nManager.forceRTL(isRTL);

  // set i18n-js config
  i18n.translations = {[languageTag]: translationGetters[languageTag]()};
  i18n.locale = languageTag;
};

Why am I getting ReferenceError: React is not defined?

$
0
0

I have a React Native application. I want to add unit tests with Jest. When I run yarn test, I get the following error:

FAIL  ./App.test.tsx
● app › can render snapshot

ReferenceError: React is not defined

   5 | describe("app", () => {
   6 |   it("can render snapshot", () => {
>  7 |     const tree = renderer.create(<App />);
     |                                  ^
   8 |     expect(tree).toMatchSnapshot();
   9 |   });
  10 | });

Here's my App.tsx:

import React from "react";
import Amplify from "aws-amplify";
import awsmobile from "./src/aws-exports";
import AppContainer from "./src/navigation/index";

Amplify.configure(awsmobile);

const App = () => {
  return (
    <AppContainer />
  );
};

Here's what I have in my App.test.tsx:

import React from "react";
import renderer from "react-test-renderer";
import App from "./App";

describe("app", () => {
  it("can render snapshot", () => {
    const tree = renderer.create(<App />);
    expect(tree).toMatchSnapshot();
  });
});

And, here's my jest.config.js:

// jest.config.js
const {defaults: tsjPreset} = require("ts-jest/presets");

module.exports = {
  ...tsjPreset,
  preset: "react-native",
  transform: {
    ...tsjPreset.transform,
    "\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
  },
  globals: {
    "ts-jest": {
      babelConfig: true,
    },
  },
  // This is the only part which you can keep
  // from the above linked tutorial's config:
  cacheDirectory: ".jest/cache",
  moduleFileExtensions: [
    "ios.js",
    "native.js",
    "js",
    "json",
    "jsx",
    "node",
    "ios.ts",
    "native.ts",
    "ts",
    "tsx",
  ],
};

Converting fingerprint.react-native from cuid to Typescript

$
0
0

The implementation in the cuid NPM library is:

import { pad } from './pad'

var globalCount = Object.keys(global);
var clientId = pad(globalCount.toString(36), 4);

module.exports = function fingerprint () {
  return clientId;
};


When converted to typescript the globalCount.toString(36) method gets the error:

Expected 0 arguments, but got 1.ts(2554)

So I assume the correct thing to do is just remove 36?

Anyone know why the 36 is there? Perhaps this is something that works in react native and I should type around it somehow?

Updating an array in SharePoint spfx using React & PnPJS

$
0
0

I'm creating a web app that allows the user to update their status and location.

I have a data list table on SharePoint with the user's name, email address, status (for example: online, offline, or busy), location (which is a select field), along with other fields.

The web app is just 2 different select fields. Which allows the user to update his status and location.

When the user accesses the page on componentDidMount() I'm getting the user's email addresses (since he's logged into SharePoint) and then filtering the data list array to view the element for his information (so looking for his email address in the MyList. The part I'm stuck at now is updating the MyList list with the selected response that the user selected.

Using PnP-JS i found this should be possible here are two links showing the update() function. https://github.com/SharePoint/PnP-JS-Core/wiki/Basic--Operations

https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Items

My code found here:

export default class SigninLocationWebpart extends React.Component<ISigninLocationWebpartProps, {Status: string, Location: string, userName: string, getEmail: string, selectedUser: any}> {

    constructor(props) {
        super(props);
        this.state = {
            Status: 'Online',
            Location: 'New York',
            userName: '',
            getEmail: '',
            selectedUser: {},

        };

        this.handleChangeStatus = this.handleChangeStatus.bind(this); 
        this.handleChangeLocation = this.handleChangeLocation.bind(this);   

    }

    handleChangeStatus(event) {
        const { value } = event.target;
        this.setState({ Status: value });
    }

    handleChangeLocation(event) {
        const { value } = event.target;
        this.setState({ Location: value });
    }


    private _onUpdate(event) { 
        event.preventDefault();

        //This is where I need help on updating list
        let list = pnp.sp.web.lists.getByTitle("MyList")

        //Instead of getting by ID i need to get by that selectUser array I believe
        list.items.getById(1).update({
            Status: this.state.Status, //User changing from Online to Offline
            Location: this.state.Location //User changing from New York to Los Angeles
        }).then(i => {
            console.log(i);
        });

    }       

    public componentDidMount() { 
        if (Environment.type === EnvironmentType.Local) {
        }
        else if (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint) {

            //This gets the current users info and sets it to username and email
            sp.web.currentUser.get().then((response : CurrentUser) => {
                //console.log(response);
                this.setState({
                    userName: response["Title"],
                    getEmail: response["Email"],
                })
            })          


            //This gets the list of all all items in the list
            pnp.sp.web.lists.getByTitle("MyList").items.get().then((items: any[]) => {
                console.log(items);

                //Comparing email from sign in user and filtering items array to get that element
                var compareEmail = this.state.getEmail;
                console.log(compareEmail);

                let selectedUser =  _.filter(items, function(item) {
                    return item.Email_x0020_Address.toLowerCase() === compareEmail.toLowerCase();
                });
                console.log(selectedUser);


            });


        }
    }



    public render(): React.ReactElement<ISigninLocationWebpartProps> {
        return (

            <div className={ styles.signinLocationWebpart }>
                <h3>Hello {this.state.userName}</h3>

                <form onSubmit={this._onUpdate}>

                    <label>
                        Check In our Out
                    </label>
                    <select name="Status" value={this.state.Status} onChange={this.handleChangeStatus}> 
                        <option value="Online">Online</option>
                        <option value="Offline">Offline</option>
                        <option value="Busy">Busy</option>
                    </select>

                    <label>
                        Location
                    </label>
                    <select name="Location" value={this.state.Location} onChange={this.handleChangeLocation}> 
                        <option value="New York">New York</option>
                        <option value="Michigan">Michigan</option>
                        <option value="Los Angeles">Los Angeles</option>
                    </select>

                    <input type="submit" value="Submit" />

                </form>

            </div>
        );
    }
}

Dropdown/Select Value Not Changing - useState

$
0
0

My dropdown menu (Material UI select) says "Search By" and then we click on it, it gives a list. When I select on of the options, I want to store the option and change the "Searchh By" to the selected option.

export default function UserSearchPage(){
  const [criteria, setCriteria] = useState('');
  const [searchItem, setSearchItem] = useState('');
  return (
    <div>
      <div className='main-content'>
        <Select 
        value = {criteria}
         onChange={value => {
          setCriteria(value);}}
        displayEmpty>
          <MenuItem disabled value="">
            <em>Search By</em>
          </MenuItem>
          <MenuItem value={1}>First Name</MenuItem>
          <MenuItem value={2}>Last Name</MenuItem>
          <MenuItem value={3}>Phone Number</MenuItem>
          <MenuItem value={4}>Email</MenuItem>
        </Select>
        <br></br><br></br>
         <SearchBar
         value= {searchItem}
         onChange={value => {
          setSearchItem(value);}}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
            </div>
          )
    </div>
  );
}

With my current onChange on the Select, I get this error on value:

Argument of type 'ChangeEvent<{ name?: string | undefined; value: unknown; }>' is not assignable to parameter of type 'SetStateAction<string>'.
  Type 'ChangeEvent<{ name?: string | undefined; value: unknown; }>' is not assignable to type '(prevState: string) => string'.

If I use this onChange:

onChange={event => setCriteria(event.target.value)}

I get an error that:

Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction<string>'.
  Type 'unknown' is not assignable to type '(prevState: string) => string'.

I tried creating a sandbox but I have no idea how to resolve the error. The code looks fine but it doesn't compile: https://codesandbox.io/s/sleepy-buck-5t7bq

React native not recognizing finally

$
0
0

Finally keyword is undefined on a classic es6 helloworld fetch example.

let isLoading = true;

fetch("https://jsfiddle.net").then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Oops, we haven't got JSON!");
  })
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.error(error); /* this line can also throw, e.g. when console = {} */ })
  .finally(function() { isLoading = false; console.log("done")});

How to get value of AnimatedInterpolation

$
0
0

My question is how to retrieve the value of an AnimatedInterpolation in react-native, without calling private code.

I create the animated value and wrap it in an interpolation like this:

  animated = new Animated.Value();
  interpolated = this.animated.interpolate({
    inputRange:[0, 1000],
    outputRange:[0, 500]
  })

I render the animation like this:

<Animated.View style={[{width: this.interpolated}]}/>

And I retrieve the animated value like this:

  this.animated.stopAnimation(v => {
    console.log(v, "", this.interpolated.__getValue());
  })

Runnable example here.

My problem is that __getValue() is a private member of AnimatedInterpolation and it gives an error when using typescript. I'm looking for a sound way to retrieve the value, similarly to how this.animated.stopAnimation is sounder than this.animated.__getValue().

Typescript StackNavigatonProps and Screen props in react-navigation v5

$
0
0

What is the best way to define type for screen's navigation prop, when screen is in different file that router? Let's say I have one file, in which I define routes:

//Router.tsx

type RootStackParamList = {
  Home: undefined;
  Profile: undefined;
}

const Stack = createStackNavigator<RootStackParamList>();

// Component rendering navigator
const Router = () => {
   .
   .
   .
}

Then I have the separate file for screen:

// Home.tsx


// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  "Home">;

type Props: {
  navigation: HomeScreenNavigationProp
}


const Home = ({navigation}: Props) => {
  .
  .
  .
}

Do I have to copy RootStackParamList over and over to every screen or create something like types.ts file and import it from there? Is there a better way to handle it? I am using navigation almost in every component.

Are there scripts or tools to help to migrate Flow to TypeScript automatically?

$
0
0

I have an old react-native module using Flow. There are several thousand lines of code. Now, I would like to migrate these codes to a new project using TypeScript. I am looking for an auto-tool to help me solve tedious type-converting works. If it would solve about 90% of problems, I would appreciate it. For example,

  • Changing all the .js file to 'ts or tsx file, like:
for f in `find . -type f -name '*.js'`;
do
git mv -- "$f""${f%.js}.ts"
done
  • convert types
// Flow
import type { Type1, Type2 } from ./dir/to/path
// Typescript
import { Type1, Type2 } from ./dir/to/path
// Flow
type Date = {
  toString: () => string,
  setTime: (time: number) => number
}

// TypeScript
interface Date {
  toString(): string;
  setTime(time: number): number;
}

// Flow 
value: ?string 
// TypeScript 
value: string | null

Any suggestions?

How to test react navigation authentication flow?

$
0
0

I'm developing a React Native application. I'm doing something like what's explained here to implement the authentication flow. So, I created an AppContainer that looks like this:

import {createAppContainer, createSwitchNavigator, createStackNavigator} from "react-navigation";
import AuthLoadingScreen from "../screens/auth/auth-loading-screen";

const AppStack = createStackNavigator({ Home: {screen: HomeScreen} });
const AuthStack = createStackNavigator({ SignIn: {screen: SignInScreen} });

const AppContainer = createAppContainer(
  createSwitchNavigator(
    {
      AuthLoading: AuthLoadingScreen,
      App: AppStack,
      Auth: AuthStack,
    },
    {
      initialRouteName: "AuthLoading",
    },
  ),
);

export {AppContainer};
export default AppContainer;

Then, here's what I have in my App.tsx:

import React from "react";
import AppContainer from "./src/navigation/index";

const App = () => {
  return <AppContainer />;
};

export default App;

And, here is my App.test.tsx:

import 'react-native';
import React from 'react';
import App from '../App';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  renderer.create(<App />);
});

Here's the jest configuration in my package.json file:

"jest": {
    "preset": "react-native",
    "setupFiles": [
      "./node_modules/react-native-gesture-handler/jestSetup.js"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|@react-native-community/*|react-navigation|react-navigation-stack|@react-navigation/.*)"
    ],
    "timers": "fake",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  },

Now, when I run yarn test, the test passes, but I get the following error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at Object.get useTheme [as useTheme] (node_modules/@react-navigation/core/lib/commonjs/index.js:3:18)
      at Object.get [as useTheme] (node_modules/react-navigation/src/index.js:169:19)
      at useTheme (node_modules/react-navigation-stack/lib/commonjs/utils/useTheme.js:65:36)
      at CardContainer (node_modules/react-navigation-stack/lib/commonjs/vendor/views/Stack/CardContainer.tsx:165:5)
      at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:5762:18) PASS  __tests__/App-test.tsx (10.657s)   ✓ renders correctly (93ms)

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10695
    The above error occurred in the <CardContainer> component:
        in CardContainer (created by CardStack)
        in View (created by View)
        in View (created by MaybeScreen)
        in MaybeScreen (created by CardStack)
        in View (created by View)
        in View (created by MaybeScreenContainer)
        in MaybeScreenContainer (created by CardStack)
        in CardStack (created by KeyboardManager)
        in KeyboardManager (created by Context.Consumer)
        in RNCSafeAreaView (created by RNCSafeAreaView)
        in RNCSafeAreaView (at src/index.tsx:28)
        in SafeAreaProvider (created by Context.Consumer)
        in SafeAreaProviderCompat (created by StackView)
        in View (created by View)
        in View (created by StackView)
        in StackView (created by StackView)
        in StackView
        in Unknown (created by Navigator)
        in Navigator (created by SceneView)
        in SceneView (created by SwitchView)
        in SwitchView (created by Navigator)
        in Navigator (created by NavigationContainer)
        in NavigationContainer (created by App)
        in App

    React will try to recreate this component tree from scratch using the error boundary you provided, NavigationContainer.

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10695
    The above error occurred in the <NavigationContainer> component:
        in NavigationContainer (created by App)
        in App

    Consider adding an error boundary to your tree to customize error handling behavior.

How can I fix that?

Problems with scroll and flat-list. Loosing the position at the selected flatList item

$
0
0

I have a flatList with expandable content. When i open 1 big content and scroll into the bottom of the list and open another the scroll are going to the bottom of the page and hidde my list. I need to scroll up to see them.

This is my flatList:

<StyledContainer>
  <FlatList
    data={faq}
    renderItem={({ item }) => (
      <ListItem
        key={item.title}
        active={activeTitle === item.title}
        onPress={onPress}
        onPressDetail={onPressDetail}
        title={item.title}
        details={item.detail}
      />
    )}
  />
</StyledContainer>

and here i have the content list (ListItem) and another list, to show details.

const internal = (
    <StyledListItem {...props}>
      <ListTitle active={active}>{title}</ListTitle>
      <Icon
        name={active ? 'remove' : 'add'}
        size={24}
        color={active ? colors.blue.secondary : colors.blue.primary}
      />
    </StyledListItem>
  );

  const touchable =
    Platform.OS === 'ios' ? (
      <TouchableOpacity onPress={toggleActive}>{internal}</TouchableOpacity>
    ) : (
      <TouchableNativeFeedback
        onPress={toggleActive}
        background={TouchableNativeFeedback.Ripple(colors.blue.primary)}>
        {internal}
      </TouchableNativeFeedback>
    );

  return (
    <StyledView>
      {touchable}
      {active && (
        <MyListDetails faqDetail={details} onPressDetail={onPressDetail} />
      )}
      <StyledLine />
    </StyledView>
  ); 

I need to gave focus to the selected item, on the first list (ListItem). Any idea how to do that?

Thanks!!!

Viewing all 6578 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>