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

ApolloClient client's Type

$
0
0

I have a function where I pass the client as a parameter and delete the token from my app etc:

  const logOut = async (client: ApolloClient<unknown>) => {...};
return (<ApolloConsumer>      {(client: ApolloClient<unknown>) => (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.buttonContainer}><Button                  onPress={() => logOut(client)}                  style={styles.button}                /></View></SafeAreaView>      )}</ApolloConsumer>  );};

Right now I am using unknownfor the ApolloClient type and it works. But what should I actually be using here?


Cannot create a React Native + TypeScript app by following official directions

$
0
0

With the following context:

$ node -vv14.8.0$ npm -v6.14.7$ yarn -v1.21.1$ tsc -vVersion 4.0.2

and following the instructions here: https://reactnative.dev/docs/typescript

I tried to create a React Native+TypeScript app with the following command:

$ npx react-native init app --template react-native-template-typescript

but got the following file structure:

enter image description here

where you can see I don't get any .tsx file (I was actually expecting that) even when I used the correspnding TypeScript template on the creation command above.

Later on they have the section: Adding TypeScript to an Existing Project, but I didn't do the the steps there because what I want to do is not exactly add TypeScript to an existing React Native project, but just creating a React Native project with TypeScript from the beginning.

Is there anything wrong I'm doing here?

Thanks for you attention.

React Native: I want to make an animation for a View, it should rotate 90deg up or down(based on a boolean) when is pressed

$
0
0

I want to make an animation to rotate 90 deg up or down if an icon from the div it's pressed.It should rotate down if show is false, and viceversa.This is my code:

const [show, setShow] = useState(false)const spinValue = new Animated.Value(0)const spin = spinValue.interpolate({inputRange: [0, 1],outputRange: ["0deg", `${!show ? "-" : ""}90deg`],})const handleIcon = async () => {  setShow(!show)  Animated.timing(spinValue, {  toValue: 1,  duration: 300,  easing: Easing.linear,  useNativeDriver: true,}).start()

}

<Animated.View style={{ transform: [{ rotate: spin }] }}><AntIcon name="left" size={22} onPress={handleIcon} /></Animated.View>

It works only for first time if I remove setShow(!show) from the handleIcon function.Do someone know what I did wrong? It is my first animation in react native.Thank you!

Hooking up React Redux to a Component in Typescript

$
0
0

I am looking to hook up React Redux to my component in typescript. I am using these docs as a template.

I have the following type defining the state I have in the Redux store (there is only one):

export interface rootState {  favourites: ImageThumbnail[]}

My component:

...interface StateProps {  favourites: NasaImageThumbnail[]}interface DispatchProps {  addFavourite: () => void  removeFavourite: () => void}interface OwnProps {  ...}const mapState = (state: rootState) => ({  favourites: state.favourites})const mapDispatch = {  addFavourite: () => ({ type: 'ADD_FAVOURITE' }),  removeFavourite: () => ({ type: 'REMOVE_FAVOURITE' })}type combinedProps = StateProps & DispatchProps & OwnProps//Component bodyexport default connect<StateProps, DispatchProps, OwnProps>(  mapState,  mapDispatch)(Component)

mapState within the connect function is producing the following error:

No overload matches this call. The last overload gave the followingerror.Argument of type '(state: rootState) => { favourites: ImageThumbnail[]; }' is not assignable to parameter of type'MapStateToPropsParam<StateProps, OwnProps, DefaultRootState>'.Type '(state: rootState) => { favourites: ImageThumbnail[]; }' is not assignable to type 'MapStateToPropsFactory<StateProps,OwnProps, DefaultRootState>'.

How to stop React Native re-rendering?

$
0
0

I'm still learning to use React Native and runnig into an issue with the stack size being exceeded but I'm unsure why. Looking at other posts I see it must be that the screen is being rerendered too many times and is stuck in a loop but how can I prevent this happening?
RaceListScreen

export function RandomRaceScreen(this: any, {navigation: navigation}) {  const [raceList, setRaceList] = useState<RaceModel[]>([]);  useEffect(() => {    const fetchedRaces: RaceModel[] = getCoreRaceList();    setRaceList(fetchedRaces);  }, []);  //number of players must be less than max number of available races  const racePressed = (raceId: number) => {    console.log('Displaying info about Race, ', raceId);    navigation.navigate('RaceLoreListScreen', {raceId: raceId});  };  const renderRaces = (item: unknown) => {    return (<RaceCard        race={item.item}        onClick={() => {          racePressed(item.item._groupId);        }}      />    );  };  const width = Dimensions.get('window').width;  return (<ImageBackground      source={require('../../assets/space_background_reduced_v1.png')}      style={globalStyles.background}><FlatList        data={raceList}        renderItem={renderRaces}        sliderWidth={width}        containerCustomStyle={style.carousel}        contentContainerCustomStyle={style.card}        itemWidth={width * 0.8}        layout="default"        removeClippedSubviews={false}      /></ImageBackground>  );}

getCoreRaceList function:

import {RaceModel} from '../../models/RaceModel';import races from '../../races/core_races.json';export function getCoreRaceList(): RaceModel[] {  let raceList: RaceModel[] = [];  for (let i = 0; i < 5; i++) {    raceList.push(      new RaceModel(races[i], races[i].name, races[i].homeworld, false),    );  }  return raceList;}

React Native: Can someone help me make a custom alert?

$
0
0

Hi can someone help me make the timeout alert box from the image below? It is the Refreshing Alert Box from Expo Mobile App, which appear when you save the code.enter image description here

Trouble fetching (useValue) from 'react-native-redash'‏

$
0
0

I'm facing a problem here, it can't fetching (useValue) from 'react-native-redash', and I tried a lot for two days and I couldn't solve it.

picture here

React Redux Undefined Object Passed into the Reducer

$
0
0

I'm working on my first React Redux application in typescript and I have a peculiar error in that the object that the reducer is receiving is 'undefined'.

types.ts

//Action typesexport const ADD_FAVOURITE = 'ADD_FAVOURITE'export const REMOVE_FAVOURITE = 'REMOVE_FAVOURITE'//Add favourite actioninterface addFavouriteAction {  type: typeof ADD_FAVOURITE,  favourite: ImageThumbnail}//Remove favourite actioninterface removeFavouriteAction {  type: typeof REMOVE_FAVOURITE,  id: string}export type favouriteActionTypes = addFavouriteAction | removeFavouriteActionexport interface favouriteState {  favourites: ImageThumbnail[]}export const initialState: favouriteState = {  favourites: []}export type rootState = ReturnType<typeof favouriteReducer>

store.ts

export const rootReducer = combineReducers({  favouriteReducer})const store = createStore(rootReducer)export default store

actions.ts

export function addFavourite (image: ImageThumbnail): favouriteActionTypes {  return {    type: ADD_FAVOURITE,    favourite: image  }}export function removeFavourite (id: string): favouriteActionTypes {  return {    type: REMOVE_FAVOURITE,    id: id  }}

reducers.ts

export function favouriteReducer(  state = initialState,  action: favouriteActionTypes): favouriteState {  switch (action.type) {    case ADD_FAVOURITE:      console.log(`am here in add fav object is: ${action.favourite}`)      return {        favourites: [...state.favourites, action.favourite]      }    case REMOVE_FAVOURITE:      return {        favourites: state.favourites.filter(          favourite => favourite.id !== action.id        )      }    default:      return state  }}

The console.log in the reducer always returns an undefined object.

The component that is calling these actions with buttons is as follows. The this.props.imageThumbnail is a valid object that is being passed into the addFavourite/removeFavourite functions.

component.tsx

const mapState = (state: rootState) => ({  favourites: state.favourites})const mapDispatch = {  addFavourite: (image: ImageThumbnail) => ({ type: 'ADD_FAVOURITE' }),  removeFavourite: (id: string) => ({ type: 'REMOVE_FAVOURITE' })}//component declaration//render method<TouchableOpacity  onPress={() => this.props.addFavourite(this.props.imageThumbnail)}/><TouchableOpacity  onPress={() => this.props.removeFavourite(this.props.imageThumbnail.id)}/>const connector = connect(  mapState,  mapDispatch)type PropsFromRedux = ConnectedProps<typeof connector>export default connector(component)

Execution flow in react native after navigation.navigate

$
0
0

Need suggestion and advice,

I am using the below 2 lines of code in react native expo component,

this.props.navigation.navigate("App"); patchUser(this.state.dataSource.userInfo.username, this.state.dataSource.userInfo.firstName,this.state.dataSource.userInfo.lastName, this.state.dataSource.lastLoginTime);

my question:

will "patchUser()" be called always ? since this.props.navigation.navigate("App") has been executed before and it takes to another component ?

regards

How to use react-native-testing-library getByRole

$
0
0

I'm trying to use getByRole in react native testing library but can't for the life of me figure out the syntax

Component in question-

<Text   accessibilityRole={'button'}  accessibilityLabel={'upvote count'}  style={[styles.upvoteText, styles.upvoteCount]}>  {upvoteCount}</Text>

and my code

expect(getByRole('button', {name: 'upvote count'} as MatcherOptions)).toBe(2)

I have a React-Native, Typescript project that works just fine but jest tests don't find modules

$
0
0

My jest tests run/pass until I start to import modules from my local project. I'm sure there is some path/setting I'm missing...

  • React native builds and runs without a problem just running tests is failing
  • I have looked at many other issues w/many different search terms...
  • I am NOT trying to mock anything ATM.
  • I'm using jest.config.js, tsconfig.test.json and babel; all included below

Here is the error

 FAIL  src/__tests__/reducers/sessionSlice.test.ts● Test suite failed to run    TypeError: Cannot read property 'type' of undefined      287 |             return state;      288 |         });> 289 |         builder.addCase(EPILOG_FLASH_INDICATION_REQUEST, (state: SessionState, action: any) => {          |                 ^      290 |             const device = getDeviceByPeripheralSelector(state, action.peripheral);      291 |             device.indicationState = action.value;      292 |             setDeviceDisplayStatus(device);      at Object.addCase (node_modules/@reduxjs/toolkit/src/mapBuilders.ts:95:33)      at builderCallback (src/reducers/sessionSlice.ts:289:17)      at executeReducerBuilderCallback (node_modules/@reduxjs/toolkit/src/mapBuilders.ts:128:3)      at createSlice (node_modules/@reduxjs/toolkit/src/createSlice.ts:227:9)      at Object.<anonymous> (src/reducers/sessionSlice.ts:156:29)      at Object.<anonymous> (src/reducers/index.ts:5:1)

Like I mentioned, react native works with these constants imported but they do not from here while running jest. So the error message is from redux but means that EPILOG_FLASH_INDICATION_REQUEST is undefined or null. So that values is not being found and imported by jest for this reducer.Here is the import from the reducer:

import {    BLE_DEVICE_DISCONNECTED,    EPILOG_FLASH_INDICATION_REQUEST,    EPILOG_FLASH_INDICATION_REQUEST_COMPLETE,    EPILOG_READY,    BLE_DEVICE_FOUND,} from 'actions';

the EPILOG_* values above are imported from src/lib/epilogX6/actions.ts

folder structure././__tests__/reducers/sessionSlice.test.ts // this is the test I'm running../android./src./src/__tests__./src/lib/epilogX6/actions.ts./src/lib/epilogX6/reducers/epilogStateReducer.ts./src/actions/index.ts // this exports * form all projects in lib and other items in this file./src/reducers ./src/reducers/sessionSlice.ts // file in here is what target of test and imports {named things} from 'actions'

Configurationsjest.config.js

module.exports = {    globals: {        __DEV__: true,        NODE_ENV: 'test','ts-jest': {            tsConfig: 'tsconfig.test.json',            diagnostics: {                warnOnly: true,            },        },    },    preset: 'react-native',    moduleFileExtensions: ['ts', 'tsx', 'js'],    // moduleNameMapper: {    //     actions: '<rootDir>/src/actions', // this worked once but didn't work for reducers found in ./src/lib    // },    moduleDirectories: ['node_modules', 'src'],    transformIgnorePatterns: ['node_modules/(?!(jest-)?react-native|@?react-navigation)'],    transform: {'^.+\\.(js|ts)$': '<rootDir>/node_modules/babel-jest',    },    testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',    testPathIgnorePatterns: ['\\.snap$', '<rootDir>/node_modules/'],    cacheDirectory: '.jest/cache',    // coverageDirectory: 'coverage',    collectCoverageFrom: ['src/**/*.{ts,tsx,js,jsx}', '!src/**/*.d.ts'],};

tsconfig.test.json

{"extends": "./tsconfig.json","compilerOptions": {"isolatedModules": false    }}

tsconfig.json

{"extends": "./tsconfig.base.json","compilerOptions": {"baseUrl": ".","paths": {            // when changed here also change in babel.config.js"*": ["node_modules/*", "*"],"actions": ["./src/actions/index"],"components/*": ["./src/components/*"],"constants/*": ["./src/constants/*"],"images/*": ["./src/images/*"],"lib/*": ["./src/lib/*"],"reducers/*": ["./src/reducers/*"],"sagas/*": ["./src/sagas/*"],"screens/*": ["./src/screens/*"],"utils/*": ["./src/utils/index"],"types": ["./src/types/index"]        },"plugins": [{"transform": "ts-optchain/transform"}]    },"include": ["./src", "src/types"],"exclude": ["./src/screens/*","./tmp/*","**/__tests__/*","**/*/*.test.*","**/__mocks__/*","node_modules","babel.config.js","metro.config.js","jest.config.js"    ]}

tsconfig.base.json

{"compilerOptions": {"target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,"module": "es2015" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,"lib": ["es6", "es2018.promise"] /* Specify library files to be included in the compilation. */,"allowJs": true /* Allow javascript files to be compiled. */,"checkJs": false /* Report errors in .js files. */,"jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,"declaration": true /* Generates corresponding '.d.ts' file. */,"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,"sourceMap": true /* Generates corresponding '.map' file. */,"noEmit": true /* Do not emit outputs. */,"isolatedModules": true /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */,"strict": false /* Enable all strict type-checking options. */,"noUnusedLocals": true /* Report errors on unused locals. */,"noUnusedParameters": true /* Report errors on unused parameters. */,"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */    }}

and just incase this is relevantbabel.config.js

module.exports = (api) => {    api.cache.using(() => process.env.NODE_ENV);    const presets = ['module:metro-react-native-babel-preset'];    const plugins = [        ['dynamic-import-node'],        ['module-resolver',            {                root: ['./src'],                extensions: ['.js', '.ts', '.tsx', '.ios.js', '.android.js'],                alias: {                    // when changed here also change in tsconfig.json                    actions: './src/actions',                    components: './src/components',                    constants: './src/constants',                    images: './src/images',                    lib: './src/lib',                    reducers: './src/reducers',                    sagas: './src/sagas',                    screens: './src/screens',                    utils: './src/utils',                    types: './src/types',                },            },        ],    ];    return {        presets,        plugins,    };};

TypeError: X is not a function, 'X' is undefined

$
0
0

I'm trying to implement the login functionality in a react native project but the following error occurs:

[TypeError: signIn is not a function. (In 'signIn({ email: data.email, password: data.password })', 'signIn' is undefined)]

function that is called when submitting the form:

  const handleSignIn = useCallback(    async (data: SignInFormData) => {      try {        console.log('chegou');        await signIn({          email: data.email,          password: data.password,        });      } catch (err) {        console.log(err);        Alert.alert('Erro na autenticação','Ocorreu um erro ao fazer login, cheque suas credenciais',        );      }    },    [signIn],  );

signIn function that is created in auth.tsx:

  const signIn = useCallback(async ({email, password}) => {    const response = await api.post('sessions', {      email,      password,    });    const {token, user} = response.data;    await AsyncStorage.multiSet([      ['@Proffy:token', token],      ['@Proffy:user', JSON.stringify(user)],    ]);    api.defaults.headers.authorization = `Bearer ${token}`;    setData({token, user});  }, []);

the repository where the project is: https://github.com/cp-yago/proffy-mobile

Firebase Cloud Functions Emulator Issue

$
0
0

I am using React Native with Firebase Firestore & Cloud Functions. In oder to test those functions locally, I use the emulator suite.

    -Application folder    --node_modules etc.    --react native stuff etc.    --some firebase configs and firebase init for client use etc.    ---Cloud Functions Folder    ----lib    ----node_modules    ----src [using typescript]    ----other stuff in Cloud Functions Package    -- other stuff in React Native Application Package

firebase deploy --only functions would transpile the ts files from src to lib and those js files would be used in production servers. But if I use the emulator, I need to transpile the ts file manually. Than the first error occurred: a gRPC version mismatch (like NodeJs Error - Failed to load gRPC binary module because it was not installed for the current system Expected directory?). Rebuilding both node_module directories did not work. I had to delete the node_modules folder in the top level "Application Folder" and do npm install.

Now I am dealing with this error:

firebase emulators:start --only functions[…]⚠  FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).    at app (/Users/user/Developer/folder/code/folderapp/node_modules/@firebase/app/dist/index.node.cjs.js:355:33)[…]

Does anyone know how to solve this issue?

React native context and deprecated super usage

$
0
0

I've been away from react native programming for a week and when I got back, after some VSCode updates, I have noticed that many of my super(props) calls in class constructors are now marked as deprecated. The reason seems to be some legacy context API issue, which is explained at this link: React Native Legacy Context

I have understood some of the issues affecting context usage from the link. However, I am now a bit confused as to whether I need to make a call to super(), super(props) or not to make the call at all. My previous understanding was that, writing a class that extends a base class, always requires a call to super(). If the base class constructor also uses any props received in the constructor, passing the props with super(props) is also required.

In my code, I almost always extend React.Component if I need a stateful component. I rarely need to use this.props in constructor()s, and if I do, I only use it to set up the initial state object, after which I deal with changes in lifecycle methods. The following is how most of my class components would look like:

class ExampleComponent extends React.Component {    constructor(props){        super(props);  // super marked as deprecated here        // super();    // super NOT marked as deprecated here        this.state = {            value: this.props.initialValue || 0        };    }    componentDidUpdate = (prevProps, prevState, snapshot) => {        // I would not actually do that, but for the sake of an example        if (this.state.value > 10){            this.setState({ value: 10 });        }    }    increment = () => {        const value = this.state.value + 1;        this.setState({ value });    }    render = () => {        return <View><Text>Current value is: { this.state.value }</Text><TouchableOpacity onPress={ this.increment }><Text>Add one!</Text></TouchableOpacity></View>;    }}

Can someone help me understand the correct usage of super in a React Native environment? I should also mention that I am using Expo SDK 38, which was released based on React 16.11. It is unclear to me whether the deprecation above also affects this version of React/React native or not.

React Navigation V5 + Typescript Error: Property 'fullName' does not exist on type 'object'

$
0
0

My Goal:

I'm trying to add Typescript typings, but having an issue with route.params.fullName. When I console.log(route.params), the object { fullName: 'John Smith' } is logged. Why is Typescript having an issue with fullName?

The weird part is that the code works and when I navigate to the screen, the header title is updated with route.params.fullName.

Error:

Property 'fullName' does not exist on type 'object'.

Functional Component:

  // React Hooks: React Navigation  const route = useRoute();  // React Hooks: Lifecycle Methods  useEffect(() => {    console.log(route.params);    // React Navigation: Set Options    props.navigation.setOptions({      // ISSUE HERE      title: route.params.fullName,    });  }, [props.navigation, route.params]);

React Native - Typescript issue

$
0
0

After a transaction I did, I started getting an error like this. How can I solve the problem?

I wrote the code in React Native as typescript

The file supporting useScrollHandler.ts in the lib folder in the react-native-dash folder in the node-modules file seems to have been deleted.

enter image description here

import React, { useRef } from "react";import { View, StyleSheet, Dimensions, Image } from "react-native";import { interpolateColor, useScrollHandler } from "react-native-redash";import Animated, { multiply, divide } from "react-native-reanimated";import Slide, {SLIDE_HEIGHT, BORDER_RADIUS} from './Slide';import Subslide from "./Subslide";import Dot from "./Dot";const { width } = Dimensions.get("window");const styles = StyleSheet.create({    container: {        flex: 1,        backgroundColor: "white",    },     underlay: {        ...StyleSheet.absoluteFillObject,        alignItems: "center",        justifyContent: "flex-end",    },    slider: {        height: SLIDE_HEIGHT,        borderBottomRightRadius: BORDER_RADIUS,    },    footer: {        flex: 1,    },    footerContent: {        flex: 1,        backgroundColor: "white",         borderBottomLeftRadius: BORDER_RADIUS,    },    pagination: {         ...StyleSheet.absoluteFillObject,            height: BORDER_RADIUS,            flexDirection: "row",            justifyContent: "center",            alignItems: "center",    },});const slides = [    {         title: "Giyim",         subtitle: "Bayan Giyim",         description: "Bayan giyimde en iyi markalar",         color: "#BFEAF5",        picture: {            src: require("../images/1.jpg"),            width: 2513,            height: 3583,        },    },    {         title: "Kozmetik",         subtitle: "Parfüm",         description: "Parfümde en iyi markalar",         color: "#BEECC4",        picture: {            src: require("../images/2.jpg"),            width: 2791,            height: 3744,        },    },    {         title: "Aksesuar",         subtitle: "Takı",         description: "Aksesuar çeşitleri",         color: "#FFE4D9",        picture: {          src: require("../images/3.jpg"),          width: 2738,          heigth: 3244,          },    },    {         title: "Butik",         subtitle: "Mağazalar",         description: "Yüzlerce mağaza seçeneği",         color: "#FFDDDD",        picture: {            src: require("../images/4.jpg"),            width: 1757,            height: 2551,        },    },];const Onboarding = () => {    const scroll = useRef <Animated.ScrollView>(null);    const {scrollHandler, x} = useScrollHandler ();    const backgroundColor = interpolateColor (x, {        inputRange: slides.map((_, i) => i * width),        outputRange: slides.map((slide) => slide.color),    });    return (<View style={styles.container}><Animated.View style={[styles.slider, { backgroundColor }]}>            {slides.map(({ picture }, index) => {                return (                    <Animated.View style={styles.underlay} key={index}><Image             source={picture.src}             style={{                 width: width - BORDER_RADIUS,                 height:                 ((width - BORDER_RADIUS) * picture.height) / picture.width,                 }}                 /></Animated.View>                );            })}<Animated.ScrollView                 ref={scroll}                horizontal                 snapToInterval={width}                 decelerationRate="fast"                 showsVerticalScrollIndicator={false}                 bounces={false}                {...scrollHandler}>                    {slides.map(({ title, picture }, index) => (<Slide key={index} right={!!(index % 2)} {...{ title, picture }} /> //Üst renkli slider kısmıüzerindeki yazıların konumlandırılması                    ))}</Animated.ScrollView></Animated.View><View style={styles.footer}><Animated.View                 style ={{ ...StyleSheet.absoluteFillObject }} // backgroundColor: "red" eklenirse Sol alt köşe rengi değişir                 /><View style= {styles.footerContent}><View style={styles.pagination} >                      {slides.map((_, index) => (<Dot                       key={index}                       currentIndex={divide(x, width)}                       { ...{index }}                       />                      ))}</View><Animated.View style={{                          flex: 1,                          flexDirection: "row",                          width: width * slides.length,                          transform: [{ translateX: multiply(x, -1) }],                      }}>{slides.map(({ subtitle, description }, index) => (<Subslide                         key={index}                         onPress={() => {                            if(scroll.current) {                                scroll.current                                .getNode()                                .scrollTo({ x: width * (index + 1), animated: true }); // İleri butonuyla bölümü atlama                            }                        }}                        last={index === slides.length - 1 }                         {...{ subtitle, description }}                         />                    ))}</Animated.View></View></View></View>    )}export default Onboarding;

React: Build Connections Among Component

$
0
0

I am a beginner of React JS. Messing around to achieve VanJS event listeners.

For layout, I decide to store things like a panel, a button as individual component.

Now, I have a component Movie and another component Button, how can I trigger state change of Movie by Button.onclick()?.

In other words, how to modify a component by the event happening on another component?

Before posting, I have read:

but tons of method followed by really confused me.

  • useState
  • componentWillMount: immediately before initial rendering
  • componentDidMount: immediately after initial rendering
  • componentWillReceiveProps: when component receives new props
  • shouldComponentUpdate: before rendering, after receiving new props or state
  • componentWillUpdate: before rendering, after receiving new props or state.
  • componentDidUpdate: after component's updates are flushed to DOM
  • componentWillUnmount: immediately before removing component from DOM

Following is a demo, which contains a Movie card and a Button, when the button is clicked, I want the background colour of the Movie card to change

React TypeScript Code Sandbox

the code:

import * as React from "react";import "./styles.css";import styled from 'styled-components';function CSSPropertiesToComponent(dict:React.CSSProperties){  let str = '';  for(const [key, value] of Object.entries(dict)){      let clo = '';      key.split('').forEach(lt=>{          if(lt.toUpperCase() === lt){              clo += '-'+ lt.toLowerCase();          }else{              clo += lt;          }      });      str += clo +':'+ value +';';  }  return str;}class Movie extends React.Component<any, any>{  public static style:React.CSSProperties|object = {      width: "300px",      height: "120px",      display: "flex",      justifyContent: "space-around",      alignItems: "center",      borderRadius: "20px",      filter: "drop-shadow(0px 1px 3px #6d6d6d)",      WebkitFilter: "drop-shadow(3px 3px 3px #6d6d6d)",      backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16),      fontSize: '2.5rem',      margin: '20px',      color: '#fff',  }  props:React.ComponentProps<any>;  state:React.ComponentState;  constructor(props:any) {      super(props);      this.props = props;      this.state = {style: Object.assign({}, Movie.style)}      this.changeColor = this.changeColor.bind(this);  }  changeColor():void{      this.setState({style: Object.assign({}, Movie.style, {backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16)})});  }  render():JSX.Element{      let StyledMovie = styled.div`          ${CSSPropertiesToComponent(Movie.style)}      `;      return (<><StyledMovie>{this.props.title}</StyledMovie></>      )  }}export default function App() {  let MV = new Movie({title: 'the Avengers'});    return (<>            {MV.render()}<button onClick={MV.changeColor}>Change Color</button></>    )}

However, when clicking on the change colour button, it doesn't work and shows a warning:

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the Movie component.

if anyone offers some suggestion, I will be so glad.

Read JSON from local file but error on map function

$
0
0

I followed a few articles on how to read json data from a local file in React and they are recommending using map function. Like https://morioh.com/p/316b1492cfda

I am getting an error

Property 'map' does not exist on type '{ updated: number; }'.ts(223)

Here is my code

import UpdatedFile from '../public/updated.json';const[Updated,setUpdated]= useState("9/9/2020");  const newdata = UpdatedFile.map((data) =>{  // This is where the error is coming    return (      setUpdated({map.updated})    )      });

This is how my JSON file looks like.

{"updated": 1599692605913}

Any idea why its not recognizing map as a valid function?

cannot read property "toFixed" of undefined

$
0
0

I have the following block of code:

export interface Record {Percentage_Emissions: number;Percentage_Emissions_Previous: number;Vs_Previous_Year: number;}const Info = ({  data}: {  data: dashboard.Results<Record>;}) => {  const styles = Styles(myStyles);  const record = data.results.records[0];  let redStyle =  record.Percentage_Emissions < 0    ? [styles.textInRed]    : [styles.textInGreen];    const percentageText =    record.Percentage_Emissions === undefined      ? `-`      : `${(          record.Percentage_Emissions * 100        ).toFixed(2)}${strings("data.percent")}`;

I just realised that the problem is with the render method, which calls:

<Text          style={[styles.text, styles.textLarge]}>{`${record.Percentage_Emissions.toFixed(2)}${strings("data.percent"        )}`}</Text>

I think the problem is that the render method assumes that Percentage_Emissions is defined, but I still don't know how to fix it.

In the emulator, the page crashes because of the error "Cannot read property "toFixed" of undefined. it is supposed to return a dash if no data was found, or else return the rounded information if it is available with conditional formatting. I can't see what is wrong with my code. Does anyone have any ideas on what is happening here?

Accessing the Wrapper Component's Props in a HOC to return a WrappedComponent with Additional Props

$
0
0

I am writing a higher order component that essentially takes in a wrapped component and uses the wrapped component props to define a set of functions and then add these functions to the props of the returned component.

This is to be done in typescript. The issue is that I do not know how to access the prop 'favourites' of the WrappedComponent and how to define the props for the HOC.

I have written out some code below to illustrate the structure.

   function withImageInfo(WrappedComponent: React.Component) {     return class extends React.Component<??> {       constructor(props: withImageInfoProps) {         super(props)         this.checkFavourited = this.checkFavourited.bind(this)       }       checkFavourited (nasaId: string): boolean {         let favourited: boolean = false         if (this.props.favourites.some(favourite => favourite.nasaId === nasaId)) {           favourited = true         }         return favourited       }       render() {         return <WrappedComponent           checkFavourited={this.checkFavourited}           {...this.props}         />       }

I have been researching and came across this article which described inheritance inversion to access the WrappedComponent's props- here is a snippet from that article in javascript illustrating this:

function iiHOC(WrappedComponent) {  return class Enhancer extends WrappedComponent {    render() {      if (this.props.loggedIn) {        return super.render()      } else {        return null      }    }  }}

The issue is that the render just seems to return the WrappedComponent using super.render() and I cannot find any documentation that describes how to/ if you should return a WrappedComponent with additional props this way.

In my HOC, I could pass in the props I need from the WrappedComponent as separate parameters like so:

function withImageInfo(WrappedComponent: React.Component, favourites: thumbnail[]) {

But I was wondering if I could access these props from the WrappedComponent that is already being passed in.

Viewing all 6214 articles
Browse latest View live


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