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

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")});

Arrow function logic in React Native CLI project

$
0
0

I created a new React Native CLI project and was thinking to convert the App component to a class based component to fix a hot reload issue when using react-navigation.

But I don't understand the logic with these two arrow functions, and how to convert it:

const App: () => React$Node = () => {
  return <NavigationWrapper />;
};

Update: the arrow question has resolved, though it didn´t help for the hot reload issue (a glitch in my logic there). See this link for a solution for that.

Converting StackNavigator from v4 to v5 React Native error for auth

$
0
0

ERROR: "The action 'NAVIGATE' with payload {"name":"Auth"} was not handled by any navigator. Do you have a screen named 'Auth'? If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators.html#navigating-to-a-screen-in-a-nested-navigator."

error message in IOS simulator

My goal is to convert React-Native stack navigator from version 4-5. I've been running into some challenges and any help would be deeply appreciated.

Nav flow: To authenticate user (with firebase) and go to a component that contains an already functional bottom-tab-navigator. Loading screen -> login -> sign up -> in the app (as a component).

This navigator is in the app.jsx file, here is the code. Note: I commented out the v4 stack-navigators, which work fine. Again, I want to convert this to the latest version 5.

import React from 'react'
// import { createAppContainer, createSwitchNavigator } from 'react-navigation'; //(v4 only)
// import { createStackNavigator } from 'react-navigation-stack'; //(v4 only)

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// screens imports 
import LoadingScreen from './screens/LoadingScreen';
import LoginScreen from './screens/LoginScreen';
import RegisterScreen from './screens/RegisterScreen';
import CategorySignin from './screens/CategorySignin';
import FeedScreen from './screens/FeedScreen';

// tab navigator 
import { AppTabs } from './AppTabs';

const Stack = createStackNavigator()

export default class App extends React.Component {

  render(){

    return(
      // trying to do...
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName="Loading"
          navigationOptions={{header: () => null}}
        >
          <Stack.Screen
            name="Loading"
            component={LoadingScreen}
          />
          <Stack.Screen
            name="Login"
            component={LoginScreen}
          />
            <Stack.Screen
            name="Register"
            component={RegisterScreen}
          />
          <Stack.Screen
            name="Sparked"
            component={AppTabs}
          />
        </Stack.Navigator>
      </NavigationContainer>

    );
  }; }


// old stack nav for auth, directs to single component (AppTabs) once logged in v4

//navigation once logged in 
// const LoginedStack = createStackNavigator({
//   // fix here 
//   Sparked: AppTabs,
// }, 
// {
//   navigationOptions: {
//     header: null,
//   },
// }
// );

// // //auth navigation
// const AuthStack = createStackNavigator({
//   Login: LoginScreen,
//   Register: RegisterScreen,

// });

// //create navigation 
// export default createAppContainer(
//   createSwitchNavigator(
//     {
//       Loading: LoadingScreen,
//       Auth: AuthStack,
//       App: LoginedStack,

//     },
//     {
//       initialRouteName: "Loading",
//       navigationOptions: {
//         header: null,
//       },
//       defaultNavigationOptions: {
//         title: 'App'
//       }
//     }
//   )
// );

react native filereader.ReadAsDataUrl results in error

$
0
0

here is my version settings sense i saw it could affect things

this is function call im using and i am just passing in a normal blob that holds a size and type variable.

private _toBase64 = (file: Blob) =>
  new Promise<string | ArrayBuffer | null>((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    resolve(reader.result);
  };
  reader.onerror = error => {
    console.log(error);
    reject(error);
  };
});

this is the error i recieve whenever this method is called

enter image description here

now the weird thing is a friend of mine has the same exact code on his computer and it works just fine

How to use react-native-permissions

$
0
0

What i want to do I want to issue an alert with react native and instruct the other party to allow location information Bluetooth,

Problem I decided to use the article below. However, looking at the examples, I can't figure out how to use them.

https://github.com/react-native-community/react-native-permissions

Q

How can I use raect-native-permission to alert me of what I want to use?

How do you use the status and settings below?

import {requestNotifications} from 'react-native-permissions';

requestNotifications(['alert', 'sound']).then(({status, settings}) => {
  // …
}

Unable to resolve module @env [closed]

How To trigger custom topBar BackButton in React-Native-Navigation

$
0
0

first of all, there are plenty of this question in github but none of them have answered at all. that is why i am asking this here.

I have an app where i have multiple pages and components. at some point, i need to trigger custom event when user pressed BackButton, i am going to show an alert to the user and then it will go back or stay on current page.

Here are what i tried so far; this is how i register a page to the navigator:


                component:
                {
                    name: 'OTP',
                    passProps: {
                        authentication,
                        rememberMe,
                    },
                    options: {
                        topBar: {
                            ...Router.topBarTypes[TopBarType.RedWithLogo],
                            rightButtons: [Router.tempIcon],
                            leftButtons: [{ <--- HERE i asign leftButton
                                    id: 'OtpBackButton',
                                }],
                        },
                        statusBar: {
                            style: 'light',
                        },
                    },
                },


                component:
                {
                    name: 'PIN',
                    passProps: {
                        authentication,
                    },
                    options: {
                        topBar: {
                            ...Router.topBarTypes[TopBarType.RedWithLogo],
                            rightButtons: [Router.tempIcon],
                            backButton: { <--- I have tried with backButton option, and leftButtons option but none of them worked.
                                id: 'PinBackButton',
                                showTitle: false,
                            },
                        },
                        statusBar: {
                            style: 'light',
                        },
                    },
                },

after i register my components to the navigator, here is how i trigger custom topBar button pressed events: Basically, i have a BaseScreen and all other screens inherits what BaseScreen have.

    constructor(props: BaseScreenProps) {
        super(props);
        this.navigationEventListener = Navigation.events().bindComponent(this); 
        Navigation.events().registerNavigationButtonPressedListener(this.navigationButtonPressed);
    }

    navigationButtonPressed({ buttonId }: { buttonId: string}) {
        switch (buttonId) {
            case 'HomeButton':
                Navigation.popToRoot(Router.ActiveComponentId);
                break;
            case 'ProfileButton':
                Router.Profile();
                break;
            case 'NotificationSettingsIcon':
                Router.NotificationSettings();
                break;  
            case 'PinBackButton':
                console.log('PIN SCREEN BACK BUTTON PRESSED');
                break;  
            case 'OtpBackButton':
                console.log('OTP SCREEN BACK BUTTON PRESSED');
                break;  
            default:
                break;
        }
    }

all of my custom triggered functions work here except the two at the bottom where i want to trigger topBars backbutton event. this is not calling at all.

I have tried componentWillUnmount but it is not what i am looking for actually.

any help will be appreciated, thanks.

Platform specific import component in react native with typescript

$
0
0

I am using react native with typescript. I have a component with the following structure

component
    - component.ios.tsx
    - component.android.tsx

Now I want to import the component. So, I am doing this:

import component from '../component/component';

But it says:

[ts] Cannot find module ../component/component

The location is correct. I need to add something to the tslint file to make it understand.

I also tried to do:

let component = require('../component/component');

This didn't give typescript error. But it gave a runtime error.

element type is invalid expected a string or a class/function but got undefined

Has anybody run into this issue? Thank you.


TypeScript React accessing array in handlesubmit()

$
0
0

I'm building an app that has 3 select fields. When the user hits submit on the form it will return a list of teachers that meet the value requirements. For example in the form you can select (3rd grade teachers, who are tenure, and are in location New York) and it will return a list of teachers that meet those requirements.

I'm stuck on the filtering part. I'm using lodash and the filter part currently works. However I want the filter function to be fired when the form is submitted. And then if the user decides to make a change to the form and resubmit for the filter function to filter again using the original TeacherList.

I believe my issue is on line this.setState = ({ TeacherList : TeacherList}); I need to make this array accessible in handleSubmit() doing something like const filteredList = _.filter(TeacherList, (v) => v.TeaherTenure === this.state.tenure);

Any ideas on how I can do this? Some more background I'm building this on SharePoint and grabbing the list using pnp.sp.web.lists. I added a comment on the Submit Handle on where I want the logic to be. When I move the TeacherList up there I get a TeacherList only refers to type, but is being used a a value here error

import * as React from 'react';
import styles from './TeacherSelector.module.scss';
import { ITeacherSelectorProps } from './ITeacherSelectorProps';
import pnp from "sp-pnp-js";
import * as _ from "lodash";

import {
    Environment,
    EnvironmentType
} from '@microsoft/sp-core-library';


interface TeacherList {
    name: string,
    address: string,
    phone: string,
    fax: string,
    TeaherTenure: string,
    TeacherGrade: string,
}


export default class TeacherSelector extends React.Component<ITeacherSelectorProps, {tenure: string, grade: string, location: string, TeacherList: string[]}> {

    constructor(props) {
        super(props);
        this.state = {
            tenure: 'yes',
            grade: 'first',
            location: 'new-york',
            TeacherList: [],
        };

        this.handleChangeTenure = this.handleChangeTenure.bind(this);
        this.handleChangeGrade = this.handleChangeGrade.bind(this);
        this.handleChangeLocation = this.handleChangeLocation.bind(this);

        this.handleSubmit= this.handleSubmit.bind(this);            

    }

    handleChangeTenure(event) {
        const { value } = event.target;
        this.setState({ tenure: value });
    }

    handleChangeGrade(event) {
        const { value } = event.target;
        this.setState({ grade: value });
    }

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

    handleSubmit(event) {
        event.preventDefault();
        alert('Tenure: ' + this.state.tenure + 'Grade: ' + this.state.grade + 'Location: ' + this.state.location);
        //Do  Filter here instead of form submit. 
    }


    public render(): React.ReactElement<ITeacherSelectorProps> {

        return (
            <div className={ styles.TeacherSelector }>
                <div className={ styles.container }>
                    <div className={ styles.row }>
                        <div className={ styles.column }>

                            <form onSubmit={this.handleSubmit}>
                                <label>
                                    Tenure (YES/NO):
                                    <select name="tenure" value={this.state.tenure} onChange={(Val: any) => this.handleChangeTenure(Val)}>
                                        <option value="yes">Yes</option>
                                        <option value="no">No</option>
                                    </select>
                                </label>

                                <label>
                                    Teaching Grade Level
                                    <select  name="grade" value={this.state.grade} onChange={this.handleChangeGrade}>
                                        <option value="first">first</option>
                                        <option value="second">second</option>
                                        <option value="third">third</option>
                                        <option value="fourth">fourth</option>                                        
                                    </select>
                                </label>

                                <label>
                                    Location
                                    <select name="location" value={this.state.location} onChange={this.handleChangeLocation}>
                                        <option value="new-york">New York</option>
                                        <option value="queens">Queens</option>
                                        <option value="new-jersey">New Jersey</option>
                                    </select>
                                </label>                                

                                <input 
                                    type="submit"
                                    value="submit"
                                    className="button" 
                                    onSubmit={this.handleSubmit}
                                />
                            </form>                         

                        </div>
                    </div>
                </div>
            </div>
        );
      }

      private _renderListAsync(): void {
        // Local Enviroment
        if (Environment.type === EnvironmentType.Local) {
            console.log('This is local');
        }
        else if (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint) {
            console.log('This is Sharepoint');
                pnp.sp.web.lists.getByTitle("Data").items.get().then((items: any[]) => {

                    const TeacherList = items.map((item) => {

                        return {
                            name: item.Full_x0020_Name,
                            address: item.Address,
                            phone: item.Phone,
                            fax: item.Fax,
                            TeaherTenure: item.Tenure,
                            TeacherGrade: item.Grade,                       
                        }
                    });
                    this.setState = ({ TeacherList : TeacherList});
                    //const filteredList = _.filter(TeacherList, (v) => v.TeaherTenure === this.state.tenure);
                    //console.log(filteredList);        
            }); 

        }
    }      


}

file reader return blobId [closed]

$
0
0

enter image description here

here is my code i am passing in an interface that hold a blob under a data:Bl

  private _toBase64 = (file: any) =>
new Promise<string | ArrayBuffer | null>((resolve, reject) => {

  const reader = new FileReader;
  debugger;
  reader.readAsDataURL(file);
  reader.onload = () => {
    resolve(reader.result);
  };
  reader.onerror = error => {
    console.log(error);
    reject(error);
  };
});

Material UI Select in Typescript

$
0
0

I have created a dropdown menu using Material UI select. It says "Search By". When we click it, it gives us a list. When I select one of the options, I want to store the option and change the "Search By" to the option selected.

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>
      </div>
    )
    </div>
  );
}

Currently, the onChange gives me 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'.

and if I use this:

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

I get:

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

React native can't toggle state

$
0
0

Whenever I call the toggle function the boolean it checks is the same which means it never truly toggles. Assuming its something to do with binding to the current value and never getting the updated value, but I'm not sure what I am supposed to do.

Here is my provider (EDITED):

import React, { createContext, useState, useCallback } from 'react';
import { Animated } from 'react-native';

type positionStyle = 'absolute' | 'relative';

export interface ITabControlService {
    animatedHeight: Animated.Value,
    positionStyle: positionStyle,
    toggle(absolute?: boolean): void,
    close(absolute?: boolean): void,
    open(): void,
}

const emptyTabControlService: ITabControlService = {
    animatedHeight: new Animated.Value(65),
    positionStyle: 'absolute',
    toggle: (absolute?: boolean) => undefined,
    close: (absolute?: boolean) => undefined,
    open: () => undefined,
};

export const TabControlContext = createContext<ITabControlService>(emptyTabControlService);


const TabControlProvider: React.FC = ({ children }) => {
    const [animatedHeight] = useState(new Animated.Value(0));  // Initial value for opacity: 0
    const [positionStyle, setPositionStyle] = useState<positionStyle>('absolute');
    const [drawerOpen, setDrawerOpen] = useState(true);

    const toggle = useCallback((absolute: boolean = true) => {
        console.log('in context and drawer is ' + drawerOpen);
        if (drawerOpen) {
            open(absolute);
        }
        else {
            close();
        }
    }, [drawerOpen]);

    const close = useCallback(() => {
        console.log('closing drawer');
        setDrawerOpen(false);
        setPositionStyle('absolute')
        Animated.timing(
            animatedHeight,
            {
                toValue: -75,
                duration: 500,
            }
        ).start();
    },[setDrawerOpen]);

    const open = useCallback((absolute: boolean = true) => {
        console.log('opening drawer');
        setDrawerOpen(true);
        setPositionStyle('absolute');
        Animated.timing(
            animatedHeight,
            {
                toValue: 0,
                duration: 500,
            }
        ).start(() => absolute ? setPositionStyle('absolute') : setPositionStyle('relative'));
    },[setDrawerOpen]);

    return <TabControlContext.Provider value={{
        animatedHeight: animatedHeight,
        positionStyle: positionStyle,
        toggle: toggle,
        close: close,
        open: open,
    }}>
        {children}
    </TabControlContext.Provider>
}

export default TabControlProvider

I can see in the logs that the same booelan is read even though toggle calls the function which then calls the setState method. clearly there is something fundemenal I am not understanding.

Any tips/hints suggestions would be much appreciated.

TypeScript types for TextInput's onChange event in React Native

$
0
0

I have a React Native Expo project using TypeScript. How can I add types for the onChange event for the TextInput?

<TextInput
      keyboardType="numeric"
      value={`${value}`}
      onChange={(e: React.FormEvent<HTMLInputElement>): void => {
        set({ value: e.target.value });
      }}
    />

I'm getting this error:

TS2339: Property "value" does not exist on type "EventTarget"

TypeScript with React Native - why does useEffect require 'current' check?

$
0
0

I'm using React Native with TypeScript and I need to set the focus on an input if certain conditions are met:

  const inputEl = React.useRef<TextInput>(null);

  React.useEffect(() => {
    if (isLast && inputEl && inputEl.current) {
      inputEl.current.focus();
    }
  }, []);

 return (
   <View>
    <TextInput
      ref={inputEl}
    />

The code above works but I get a TypeScript error if I remove the inputEl.current check:

  React.useEffect(() => {
    if (isLast && inputEl) {
      inputEl.current.focus();
    }
  }, []);

TS2531: Object is possibly 'null'.

Why is this happening? I'm checking for the existence of inputEl, so if it does exist wouldn't it always have a current property?

Also is my code correct or should the type be specified as:

const inputEl: React.RefObject<TextInput> = React.useRef(null);

onCompleted() for GraphQL Mutation giving console error

$
0
0

If the mutation is not successful, I want to show the user a message.

Code:

function submitForm(RemoveUserMutation: any) {
    const { email} = state;
    if(email){
      RemoveUserMutation({
        variables: {
            email: email,
        },
    }).then(({ data }: any) => {
      console.log('info: ', data.deleteUser);
    })
    .catch(console.log)
    }
  }

  return (
    <Mutation mutation={RemoveUserMutation}>
      {(RemoveUserMutation: any) => (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}
      >
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched
          } = props;
          const change = (name: string, e: any) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
            setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
          };
          return (
            <div className='main-content'>
              <form style={{ width: '100%' }}
               onSubmit={e => {e.preventDefault();
                submitForm(RemoveUserMutation)}}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <br></br>
                  <Button
                  type="submit"
                  disabled={!isValid || !email}
                    style={{
                      background: '#6c74cc',
                      borderRadius: 3,
                      border: 0,
                      color: 'white',
                      height: 48,
                      padding: '0 30px',
                    }}
                  >
                    Remove User</Button>
                </div>
              </form>
            </div>
          )
        }}
      </Formik>
    </div>
      )}
     </Mutation>
  );
}

Fow now, I tried to print it on console but I get an error on onCompleted that:

Type 'void' is not assignable to type '((data: any) => void) | undefined'.ts(2322)

I tried this too but doesn't really help since idk how to show the user a message that the mutation is successful or not. It could be a typography too, or alert.

onCompleted= {(e: any) => setStatus(true)}


Transpiling ActiveRecord objects to TypeScript types for non-mono repository

$
0
0

I've recently started development on what will be come a rather large mobile application (React Native) that consumes a Ruby on Rails API (in API mode).

On the frontend I've used TypeScript extensively throughout the code but I am having issues with how to approach building types and interfaces for data received through API requests. I've heard about transpiling C# database models into TypeScript types - but I can't find anything similar for Ruby on Rails. The only thing I've been able to find is how to handle types in mono-repos where both the frontend and backend is in a single repository.

I could build my types manually on the frontend but I feel like this wouldn't be sustainable over the long term, especially when new developers join the project.

Is there any gems out there for this or would I have to write it myself? Am I approaching the issue incorrectly?

unable to run react-native test with jest

$
0
0

jest keeps failing on react-native 0.61.5

https://github.com/mindsgn/OrbytDapp/issues/8

yarn run v1.21.1 $ jest FAIL tests/App-test.js ● Test suite failed to run

ReferenceError: __DEV__ is not defined

  3 |  */
  4 | 
> 5 | import 'react-native';
    | ^
  6 | import React from 'react';
  7 | import App from '../App';
  8 | 

  at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native-implementation.js:353:1)
  at Object.<anonymous> (__tests__/App-test.js:5:1)

Test Suites: 1 failed, 1 total Tests: 0 total Snapshots: 0 total Time: 2.597s Ran all test suites. error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Snackbar not opening after GraphQL Mutation

$
0
0

I want my snackbar to open if the mutation is not successful. In this case, handleOpen() is called.When I hit the button, the mutation takes place and my page crashes. I get an error that

TypeError: undefined is not an object (evaluating 'children.props.style')

When I remove the setStatus from my handleOpen function, the page doesn't crash. Oops is printed.

For my Snackbar, I am using open={status}

Here's the full code:

export default function RemoveUserPage() {
  const [state, setState] = useState({
    email: '',
  });  
  const [status, setStatus] = useState(false);
  // onCompleted= {(e: any) => setStatus(true)}

  function submitForm(RemoveUserMutation: any) {
    const { email} = state;
    if(email){
      RemoveUserMutation({
        variables: {
            email: email,
        },
    }).then(({ data }: any) => {
      console.log('info: ', data.deleteUser);
    })
    .catch(console.log)
    }
  }
//In my case, the mutation is unsucessful so handleOpen()is called
  const handleOpen = () => {console.log('Oops');setStatus(true)}
  return (
    <React.Fragment>
    <Mutation mutation={RemoveUserMutation}
    onError={(err: any) => {
      handleOpen()
    }}
    >
      {(RemoveUserMutation: any) => (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}
      >
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched
          } = props;
          const change = (name: string, e: any) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
            setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
          };
          return (
            <div className='main-content'>
              <form style={{ width: '100%' }}
               onSubmit={e => {e.preventDefault();
                submitForm(RemoveUserMutation)}}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <br></br>
                  <Button
                  type="submit"
                  disabled={!isValid || !email}
                    style={{
                      background: '#6c74cc',
                      borderRadius: 3,
                      border: 0,
                      color: 'white',
                      height: 48,
                      padding: '0 30px',
                    }}
                  >
                    Remove User</Button>
                </div>
              </form>
            </div>
          )
        }}
      </Formik>
    </div>
      )}
     </Mutation>
     <Snackbar
          open={status}>
        </Snackbar>
        </React.Fragment>
  );
}

The Keyboard cover TextInput form when I run the React Native Expo app

$
0
0

When I run the app with expo and use my DateFormInput component the Keyboard covers TextInput. I tried to use I , "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-keyboard-aware-scroll-view" and "react-native-keyboard-spacer", but none of them worked on either IOS or Android.

Here is the component I where I render my TextInput (DateFormInput):

import React from 'react';
import {
  Text,
  StyleSheet,
  View,
  KeyboardAvoidingView,
  ScrollView,
} from 'react-native';

import Box from './Box';
import Button from './Button';
import DateFormInput from './DateFormInput';
import { isValidDate } from '../util';
import strings from '../strings';

interface Props {
  handleSubmit: (formName: string) => void;
  handleOnChange: (formName: string, input: string) => void;
  handleCancelButton: (formName: string) => void;
  toggleInputError: (formName: string, clear?: boolean) => void;
  inputFormText: string;
  inputError: boolean;
  formName: string;
}

export const DDCAndDTNInputForm: React.FC<Props> = (props: Props) => {
  return (
    <Box style={styles.box}>
      <Text>
        {props.formName === 'DrugTest' ? strings.DrugTestDate : strings.DDCDate}
      </Text>
      <View style={{ flex: 1 }}>
        <KeyboardAvoidingView behavior="padding" style={styles.box}>
          <ScrollView style={{ flex: 1 }}>
            <DateFormInput
              type={'datetime'}
              options={{ format: 'MM/DD/YYYY' }}
              placeholder={'MM/DD/YYYY'}
              value={props.inputFormText}
              error={props.inputError}
              onChangeText={text => props.handleOnChange(props.formName, text)}
              onBlur={e => {
                isValidDate(props.inputFormText)
                  ? props.handleSubmit(props.formName)
                  : props.toggleInputError(props.formName, true);
              }}
            />
          </ScrollView>
        </KeyboardAvoidingView>
      </View>

      <Text style={{ color: 'red' }}>
        {props.inputError ? 'Type a valid date' : null}
      </Text>

      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-around',
        }}
      >
        <Button
          viewStyle={styles.linkButton}
          title={'CANCEL'}
          onPress={() => {
            props.handleCancelButton(props.formName);
          }}
        />

        <Button
          viewStyle={styles.linkButton}
          title={'SAVE DATE'}
          onPress={() => {
            isValidDate(props.inputFormText)
              ? props.handleSubmit(props.formName)
              : props.toggleInputError(props.formName, true);
          }}
        />
      </View>
    </Box>
  );
};

export default DDCAndDTNInputForm;

const styles = StyleSheet.create({
  linkButton: {
    paddingVertical: 8,
    paddingHorizontal: 16,
    marginVertical: 8,
    flex: 1,
  },
  box: {
    padding: 24,
    marginBottom: 16,
    flex: 1,
  },
});

This is my custom InputText (DateFormInput):

import React from 'react';
import {
  Text,
  StyleProp,
  TextStyle,
  StyleSheet,
  KeyboardType,
  View,
  NativeSyntheticEvent,
  TextInputFocusEventData,
} from 'react-native';
import { TextInputMask } from 'react-native-masked-text';

import { textStyle, colors } from '../styles';

const styles = StyleSheet.create({
  input: {
    marginVertical: 8,
    padding: 16,
    borderWidth: 2,
    borderColor: colors.sectionBackground,
    borderRadius: 8,
    backgroundColor: colors.white,
  },
});

export default (props: {
  label: string;
  value: string;
  labelStyle: StyleProp<TextStyle>;
  keyboardType?: KeyboardType;
  onChangeText: (text: string) => void;
  onBlur?: (e: NativeSyntheticEvent<TextInputFocusEventData>) => void;
  error?: boolean;
  defaultValue?: string;
}) => (
  <View style={{ flexDirection: 'column', alignContent: 'stretch' }}>
    <Text style={[textStyle.formLabel, props.labelStyle]}>{props.label}</Text>
    <TextInputMask
      type={'datetime'}
      options={{ format: 'MM/DD/YYYY' }}
      placeholder={'MM/DD/YYYY'}
      style={[styles.input, props.error ? { borderColor: colors.red } : null]}
      value={props.value}
      onChangeText={props.onChangeText}
      onBlur={props.onBlur}
    />
  </View>
);

TapGestureHandler not triggering onGestureEvent but onHandlerStateChange triggers twice

$
0
0

I'm trying to use the react-native-gesture-handler library to add double click event when a picture is tapped.

the issue I'm running into is the onGestureEvent is never being triggered and onHandlerStateChange is being triggered twice even if I've only clicked it once. on one click it will trigger show the alert fade away then show the alert again.

the second part of this is my number of taps is 2 so it shouldn't event trigger on one tap. this is all wrapped within a flatlist if that matters.

                            renderItem={({ item }) => {
                            return (
                                <Fragment>
                                    {this.state.isExpandable && (

                                        <TapGestureHandler
                                            onHandlerStateChange={this.showImageOverlay}
                                            onGestureEvent={this.finalEvent}
                                            numberOfTaps={2}
                                        >
                                            <Image
                                                style={{ ...collapsibleImagesStyles.Image, height: 540 / 4, width: 540 / 2.2 }}
                                                source={{ uri: item }} />

                                        </TapGestureHandler>
                                    )
                                    }
                                </Fragment>
                            )

                        }}
                        keyExtractor={(item, index) => index.toString()}




    private finalEvent = (event: TapGestureHandlerGestureEvent) => {

    if (event.nativeEvent.state = State.BEGAN)
    alert(JSON.stringify('FINAL BEGAN'))
    if (event.nativeEvent.state = State.ACTIVE)
        alert(JSON.stringify('FINAL ACTIVE'))
    if (event.nativeEvent.state = State.END)
        alert(JSON.stringify('FINAL END'))
}

private showImageOverlay = (event: TapGestureHandlerStateChangeEvent) => {

    if (event.nativeEvent.state = State.ACTIVE)
        alert(JSON.stringify('ACTIVE'))
}
Viewing all 6418 articles
Browse latest View live


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