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

add radio buttons with custom text

$
0
0

I have a component with icons and some text.

const criteriaList = ['New','Freunde',];export const FilterCriteriaList: React.FunctionComponent = () => {  //const [checked, setChecked] = React.useState('first');  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: string) => (<View key={item}><View style={styles.criteriaRow}><TouchableOpacity              style={styles.iconContainer}              onPress={() => console.log('dhjksds')}><Icon                style={styles.icon}                name="circle-thin"                color="#31C283"                size={moderateScale(20)}              /></TouchableOpacity>            {/* <RadioButton        value="first"        //status={ checked === 'first' ? 'checked' : 'unchecked' }        onPress={() => setChecked('first')}      /> */}<Text style={styles.text}>{item}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};

The TouchableOpacity doesn't work properly and nothing happens when I click on the icon. Also, the touchable opacity covers a lot more area than just the icon. Changing the height isn't feasible either since it ruins the design.

So, I am trying to use radio buttons from

import { RadioButton } from 'react-native-paper';

I commented out the TouchableOpacity and tried using Radiobuttons for testing but it gives me an error regarding unrecognisable material ui..The app crashes before I can even read the full error.

How exactly can I use radio buttons here? My component should look like it looks right now.enter image description here


remove button outline native-base

$
0
0

I am trying to wrap an icon in a button. Like this:

<Button              style={styles.radioButton}              onPress={() => {                console.log('hdjwk');              }}><Icon                style={styles.icon}                name="circle-thin"                color="#31C283"                size={moderateScale(20)}              /></Button>...  radioButton: {    backgroundColor: 'white',    borderRadius: 0,    borderColor: 'white',  },  icon: {    paddingTop: moderateScale(12),  },

However, when I wrap my icon with the button, the icon is pushed downwards and an outline starts to appear even though I have set the borderRadius as 0. How can I fix this such that it looks natural and there's no distinction between the background screen and the icon?

enter image description here

Placing a marker by clicking anywhere on the mapview screen in react native

$
0
0

My problem is, im trying to make my mapView so everytime I tap on it a marker is created and the marker's latitude and longitude are sent to the console in order to send them using fetch, I found something similar here but it's made in a class and im trying to make it in a function.

Heres the code:

  constructor(props) {  super(props)  this.state = {    region: {      latitude: 24.92009056750823,       longitude: 67.1012272143364,      latitudeDelta: 0.1,      longitudeDelta: 0.1    },    markers: []  }}<MapView style={styles.map} region={this.state.region}onPress={(e) => this.setState({ markers: [...this.state.markers, { latlng: e.nativeEvent.coordinate }] })}>{    this.state.markers.map((marker, i) => (<MapView.Marker key={i} coordinate={marker.latlng} />    ))}</MapView>  

TouchableOpacity and onPress for Icons

$
0
0

I am trying to use onPress for icons. For this, I thought of using TouchableOpacity but nothing happens when I click on the icon. I don't see any console logs.

I also tried wrapping the icon in an additional View but that doesn't work either.

const criteriaList = ["Nur Frauen","Freunde Zweiten Grades",]export const FilterCriteriaList: React.FunctionComponent = () => {  return (<View style={styles.container}><View style={styles.horizontalLine} />          {criteriaList.map((item: string) => (<View key={item}><View style={styles.criteriaRow}><TouchableOpacity style={styles.iconContainer} onPress={()=>console.log('dhjksds')}><Icon style={styles.icon} name="circle-thin" color="#31C283" size={moderateScale(20)}/></TouchableOpacity><Text style={styles.text}>{item}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};const styles = StyleSheet.create({  container: {    flex: 1,  },  criteriaRow: {      flexDirection: 'row',      paddingLeft: moderateScale(25),  },  horizontalLine: {    width: '100%',    height: moderateScale(1),    backgroundColor: '#E0E0E0',  },  text: {    paddingLeft: moderateScale(15),    paddingBottom: moderateScale(15),    marginBottom: moderateScale(15),    paddingTop: moderateScale(15),  },  icon: {      paddingTop: moderateScale(12),  },  iconContainer: {      backgroundColor: 'red',  }});

enter image description here

It looks like this and I click in the middle of the circle icon.

What else can I try?

enter image description here

First onchange checkbox execution doesn't run correctly function React Native Help pls

$
0
0

In my first execute my function doens't work.I need a checkbox that adds or subtracts numbers. but it doesn't work on the first run, only on the next ones. console.log () works, but it only adds or subtracts in the second run onwards.

  constructor(props) {    super(props);    this.state = {      valOp1: false,      cotacao: 0.0,      cont: 1,    };  }  op1 = value => {{    this.setState({ valOp1: !this.state.valOp1});     if(this.state.valOp1 == true){      console.log('selected');      this.setState({ cotacao: this.state.cotacao + 10});      console.log(this.state.cotacao);    }    else if(this.state.valOp1 == false){      console.log('not selected');      this.setState({ cotacao: this.state.cotacao - 10});      console.log(this.state.cotacao);    }    }  this.funcop1();}  funcop1(){  }  render(){    return(<View><TextInput    label="Valor Fipe"    value={this.state.val}    maxLength={11}    keyboardType="numeric"    onChangeText= {(val) => this.setState({val})}    /><View style={styles.container}><Text style={styles.checkTitle}>Opcionais:</Text><View style={styles.checkboxContainer}><CheckBox         value={!!this.state.valOp1}         onValueChange={this.op1}         style={styles.checkbox}        /><Text style={styles.label}>Do you like React Native?</Text></View></View></View>    );  }}```

change Icon after clicking on it

$
0
0

I have a component that looks like this:

const criteriaList = ['Nur Frauen','Freunde Zweiten Grades',];export const FilterCriteriaList: React.FunctionComponent = () => {  const [state, setState] = useState(false);  useEffect(() => {    console.log('state is,', state);  });  const myFunction = () => {    console.log('checking state', state);    if (state == false) {      setState(true);    } else {      setState(false);    }  };  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: string, index: number) => (<View key={index}><View style={styles.criteriaRow}><TouchableOpacity               onPress={() => {                myFunction();              }}><Icon                name="circle-thin"                color="#31C283"                size={moderateScale(20)}              /></TouchableOpacity><Text style={styles.text}>{item}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};

Currently, I am using the circle-thin icon. I want to change it such that everytime I click on an icon, it changes to the dot-circle-o icon. Like radio buttons. However, I am not quite sure how to do so.

I thought of using ternary operators but since I am mapping my fields Idk how to setStates collectively. Maybe using the index? I don't want to make a separate state for each field. Here's a similar snack demo:

https://snack.expo.io/toTSYc2fD

I want to be able to select multiple/unselect options. I don't want to apply the same rule on all fields together.

Note: the onPress function can also be used on the Icon directly instead of the TouchableOpacity (though it is not preferred)

How to set autocomplete for react native elements input on iOS?

$
0
0

I am trying to set correct autocomplete suggestions on my registration form.I am using react native elements input, I have set username, email and password field.On email field I have set

textContentType={'emailAddress'}keyboardType={'email-address'}autoCompleteType={'email'}

and even so the keyboard is offering me only passwords for autocomplete.But even weirder is that if I add another input the email autocomplete works fine.Does anyone know is there anything I should be focusing on?

reset settings of one component from another

$
0
0

I have a screen where I am using some text and another component called FilterCriteriaList which has some custom buttons that change their color when we click on them.

On my main screen, I want to press on the text and reset the settings in the FilterCriteriaList component. This could be done by setting all options[index].checked to false. However, I cannot figure out how to do so such that we can select the buttons again as well.

type FilterCriteriaListProps = {  deleteAll: boolean;};type CriteriaList = {  title: string;  checked: boolean;};const criteriaList = [  { title: 'Nur Frauen', checked: false },  { title: 'Freunde Zweiten Grades', checked: false },  { title: 'Nichtraucherfahrzeug', checked: false },  { title: 'Mit min. 4 Sternen bewertet', checked: false },  { title: 'Automatische Zusage', checked: false },];export const FilterCriteriaList: React.FunctionComponent = () => {  const [selected, setSelected] = useState(criteriaList);  const handleChange = (index: number) => {    const options = [...selected];    options[index].checked = options[index].checked ? false : true;    setSelected(options);  };  return (<View style={styles.container}><View style={styles.horizontalLine} />      {criteriaList.map((item: CriteriaList, index: number) => (<View key={index}><View style={styles.criteriaRow}><Icon              name={item.checked ? 'dot-circle-o' : 'circle-thin'}              color="#31C283"              size={moderateScale(20)}              onPress={() => handleChange(index)}            /><Text style={styles.text}>{item.title}</Text></View><View style={styles.horizontalLine} /></View>      ))}</View>  );};

On main screen:

  const [deleteAll, setDeleteAll] = useState(false);  const deleteAllFilters = () => {    setDeleteAll(true);  };<Text style={styles.deleteAllText} onPress={()=>{deleteAllFilters}}>DELETE ALL</Text>...<FilterCriteriaList/>

Snack Expo:https://snack.expo.io/dh3fk53zf


React Native - Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

$
0
0

I have started getting this error Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication) since yesterday, my application was working and all of sudden it broke.

Google for hours most of them asked to -Delete your yarn.lock/package-json.lock file and run yarn/npm install.Then try clearing cache with npx react-native start --reset-cache but none of iit worked.

Tried deleting re-building the app but it fails with the same error.

My - index.js

/**

  • @format*/
import App from './App';import {name as appName} from './app.json';AppRegistry.registerComponent(appName, () => App);

react Native version

"react": "16.13.1","react-native": "0.63.2",

Dependencies all i have are

package.json

"dependencies": {"@ptomasroos/react-native-multi-slider": "^2.2.2","@react-native-community/datetimepicker": "^2.6.0","@react-native-community/masked-view": "^0.1.10","@react-native-community/picker": "^1.6.5","@react-native-community/slider": "^3.0.3","@react-navigation/bottom-tabs": "^5.7.2","@react-navigation/material-top-tabs": "^5.2.14","@react-navigation/native": "^5.7.2","@react-navigation/stack": "^5.8.0","@types/react-native-svg-charts": "^5.0.3","@types/react-redux": "^7.1.9","lottie-ios": "3.1.8","lottie-react-native": "^3.5.0","moment": "^2.27.0","react": "16.13.1","react-moment": "^0.9.7","react-native": "0.63.2","react-native-gesture-handler": "^1.7.0","react-native-reanimated": "^1.10.1","react-native-safe-area-context": "^3.1.1","react-native-screens": "^2.9.0","react-native-svg": "^12.1.0","react-native-svg-charts": "^5.4.0","react-native-swipe-list-view": "^3.2.3","react-native-swiper": "^1.6.0","react-native-tab-view": "^2.15.0","react-redux": "^7.2.1","redux": "^4.0.5"  }

Handling non null assertions in react native application

$
0
0

I have authContext in my react native application with a token property, it can be string | null.
I have some protected routes, meaning I'm not showing links unless user is logged in and token exists.
On this routes I'm trying to use this token, but TypeScript saying it could be null, which makes sense, but I know that it couldn't.
I know I can use non assertion operator token!, but is there an alternative to this problem because it's happening very often often in my code and seems there should be a better way to approach this problem. Appreciate any thoughts on this, thanks.

set Initial State with graphql returned data

$
0
0

I have a redux setup that looks like this:

const INITIAL_STATE = {  endPoint: { street: '', coordinates: [] }, //[13.3969, 52.5182]  startingPoint: { street: '', coordinates: [] }, //[13.413215, 52.521918]  favouritePoint: { street: '', coordinates: [] },  //favouriteLocations: getFavouritePlaces(),  favouriteLocations: [    {      name: 'House',      street: 'Nowhere',      coordinates: [8, 53],    },  ],  addressesFoundList: [],};export default (  state: LocationsType = INITIAL_STATE,  //state: any = INITIAL_STATE,  action: any,) => {  switch (action.type) {    case LOCATIONS.SET_END_POINT:      return { ...state, endPoint: action.payload };    case LOCATIONS.SET_FAVOURITE_POINT:      return { ...state, favouritePoint: action.payload };    default:      return state;  }};

Later on, I use its values like this:

 const myFavouriteDestinations = useTypedSelector(    (state) => state.locations.favouriteLocations,  );

Now, instead of hardcoding values, I want to set favoriteLocations after obtaining data from graphql. For that, I wrote this function and called it like this favouriteLocations: getFavouritePlaces(),

const getFavouritePlaces = () => {  const { data, error, refetch } = useGetPersonalFavouritePlacesQuery();  if (data) {    console.log('from reduxxx', data.personalFavouritePlaces.nodes);    const favoriteLocations = data.personalFavouritePlaces.nodes.map((node: FavouritePlace)  => {      return {        name: node.customisedName,        street: node.placeName,        coordinates: node.center.coordinates      }    })    console.log('from reduxxx', favoriteLocations);    return favoriteLocations;  }  else {    const favouriteLocations = [      {        name: 'House',        street: 'Nowhere',        coordinates: [8, 5],      },    ]    return favouriteLocations;  }}

However, this doesn't work and I end up with an invalid hook call error. Which doesn't make sense to me since I am using the graphql hook inside a function already. What else can I do to set the favoriteLocations data?

extract values from an object with forEach

$
0
0

I run a graphql query and obtain data (data.personalPlaces), an object that looks like this:

nodes: (4) [{…}, {…}, {…}, {…}]

where each node is like this:

0:customisedName: "HomeOfBestFriendAlice"id: 1placeName: "Husbrok 1, 26127 Oldenburg, Deutschland"center: "Zes"__typename: "FavouritePlace"__proto__: Object

I want to iterate through all nodes such that I can make an array out of it

  favouriteLocations: [    {      name: 'Zu Hause',      street: 'Müllersweg',    },    {      name: 'Büro',      street: 'Philipp-Reis-Gang',    },    {      name: 'KaffeeHaus',      street: 'Cloppenburgerstr.',    },  ],

where name is the customisedName and street is the placeName from my original data. How can I achieve this?

Data shape:

{"data": {"personalFavouritePlaces": {"nodes": [        {"placeName": "Paris, France"        },      ]    }  }}

calling a function from a const value

$
0
0

I have an initial state const item that looks like this:

const INITIAL_STATE = {  endPoint: { street: '', coordinates: [] }, //[13.3969, 52.5182]  startingPoint: { street: '', coordinates: [] }, //[13.413215, 52.521918]  favouritePoint: { street: '', coordinates: [] },  favouriteLocations: {getFavouritePlaces()},  // favouriteLocations: [  //   {  //     name: 'Zu Hause',  //     street: 'Müllersweg',  //     coordinates: [8.217462, 53.13975], //[8.258844, 53.119525],  //   },  //   {  //     name: 'Büro',  //     street: 'Philipp-Reis-Gang',  //     coordinates: [8.258844, 53.119525], //[8.217462, 53.13975],  //   },  //   {  //     name: 'KaffeeHaus',  //     street: 'Cloppenburgerstr.',  //     coordinates: [8.211, 53.113],  //   },  // ],  addressesFoundList: [],};

Instead of the hardcoded value, I am trying to call a function for favouriteLocations that will return an object of the same type. However, currently this does not call my function.

My function looks like this:

const getFavouritePlaces = () => {return ...}

Later on, I will be using this initial state for my redux setup.

The value of $input has a wrong structure., Location: [object Object], Path: undefined

$
0
0

I am trying to run a graphql mutation. On the playground, it works like this:

mutation {  addFavouritePlace(    input: {      center: { coordinates: [4, 9], type: POINT },      customisedName: "School",      placeName: "Schonebeck"    }  ) {    id  }}

In my code, I am trying to run it like this:

mutation addFavouritePlace($input: AddFavouritePlaceInput!) {  addFavouritePlace(input: $input) {    id  }}...  const [addFavouritePlace, { data, error }] = useAddFavouritePlaceMutation({    onCompleted: () => {      console.log('yas');      console.log('HDUIAJS', data);    },    onError: () => {      console.log('nooo');      console.log('HDUIAJS', error);    },  });..        addFavouritePlace({          variables: {            input: {              center: {                coordinates: [8,8],                type: GeoJsonGeometryType.Point,              },              customisedName: 'NewSchool',              placeName: "Bremen Hbf 34"            },          },        });

However, I keep getting an error that:

The value of $input has a wrong structure., Location: [object Object], Path: undefined. The error from console.log('HDUIAJS', error); undefined though.

I am certain that the $input: AddFavouritePlaceInput! is correct. Where else could I be going wrong?

Edit:

On the playground, the above mutation would work. However, if I change it to:

mutation addFavouritePlace($input: AddFavouritePlaceInput!) {  addFavouritePlace(input: $input) {    id  }}

and write this in the query variables section:

{"input": {"center": {"coordinates":[4,5],"type": "POINT"},"customisedName": "NewLoc", "placeName": "Sheesh"}}

I get the same error because of the coordinates field. Epected value type of Position. Now Position is simply defined as an array of numbers. Which is exactly what I am passing.

Usage of React Native Debugger with typescript

$
0
0

To setup React Native debugger we have to declare a composer like this:

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || composeconst store = createStore(  rootReducers,  composeEnhancers(applyMiddleware(thunk)))

But when using with typescript TS Compiler says: Cannot find name 'window'.ts(2304)

Already tried changing the key lib in tsconfig.json to this:

"lib": ["es6", "DOM"]

But the error changes to:

Property '__REDUX_DEVTOOLS_EXTENSION_COMPOSE__' does not exist on type 'Window & typeof globalThis'.ts(2339)

How can I get a value from an array, when the person clicks, to send it to a function

$
0
0

To explain a bit, I have an array that shows me all the providers and the name of each one

          {orderByProviderBrand && this.sortingByAlphabet().map(r => {            return (<div              key={r.id}              className="provider-card"              onClick={() =>  this.props.history.push(`/home-providers/${r.id}`, { singleProviderId: r.id })}>                {r.disponible === true && <div className='logo' style={{ backgroundImage: `url(${process.env.REACT_APP_BFF_IMAGE}providers/${r.logo})` }}></div>}<div className='name-provider'>{r.name}</div></div>            )          })}

I need that when the user clicks on one of the providers, remove the name of that provider, to send it in a function that receives the name string.

export const moreInfoProvider = (providerName:string) => {FirebaseAnalytics.logEvent({name: "more_info",  params: {    provider_name:providerName    }}); }

This is in another class, import {moreInfoProvider} from '../firebase/firebaseTags' With that import I call the function and where I can get the name, send that parameter and travel there, but I can't get the name, I need help, please

Property 'scrollToIndex' does not exist on type 'FlatList'

$
0
0

I'd like to understand the reason for this warning/error: 'Property 'scrollToIndex' does not exist on type 'FlatList<School>'

I have a React Native Snap Carousel list that should be scrolling another list on snap.

I created a ref for the list that I want to scroll with const schoolList = useRef<FlatList<School>>(null);The assigned the ref to that list with ref={schoolList}And my carousel does this:

<BottomCarousel  ...  onSnapToItem={(index) => {    schoolList.current?.scrollToIndex({ animated: false, index });  }}/>

The error I get is on this line: schoolList.current?.scrollToIndex({ animated: false, index });

So I did some digging. scrollToIndexdefinitely exists for FlatList.What am I missing?

react native country code prefix for text input

$
0
0

Trying to set up a form that takes a customer's address and phone number, but the API only accepts the phone number with the country code attached. So I need to add it in through the code.

I've tried it with my code below, but it seems like it's always leaving out the last number.

export default function ShippingAddressForm(props: Props) {  let { address, onChangeAddress } = props;  let [phoneState, setPhoneState] = useState<string>('');<TextInput    label={t('Phone Number')}    textContentType="telephoneNumber"    value={phoneState}    onChangeText={(number) => {      setPhoneState(number)      let phone = '+61'+ phoneState      onChangeAddress({ ...address, phone })    }}  />}

Building an app on Expo with react native typescript

Typescript issue in Styled component Button ( React-Native )

$
0
0

this code :

import React from 'react';import styled from 'styled-components/native';const Button = styled.Button`  color: palevioletred;`;interface Props {}interface State {}export default class App extends React.Component<Props, State> {  render() {    return <Button> Test btn</Button>;  }}

throws this error :

No overload matches this call.Overload 1 of 2, '(props: Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ... | "disabled"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ... | "disabled">': onPress, titleOverload 2 of 2, '(props: StyledComponentPropsWithAs<typeof Button, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof Button, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ...

i HAVE installed @types/styled-componentswhy this occurs?

Avoid object is possibly undefined

$
0
0

I'm trying make an Input that can handle array(so inputs are dynamic n+) with formik in react native. It works but typescript complains with "object is posibly undefined" and "Element implicitly has an 'any' type because index expression is not of type 'number'" also the code is really ugly I don't like it, is there another way to make this ?. I think my problem is defined the type of formikProps in FormikPropsWrap.

formikProps have errors, touched and values property but if I didn't interact with the form errors and touched can be empty like this.

{values: {menus: [{name: 'dish1'price: '10'}, ...]}errors: {},touched: {}}

after interact

{values: {menus: [{name: 'dish1'price: '10'}, ...]}errors: {menus: [{name: 'errorx', price: 'error' }],touched: {menus: [{name: true, price: true }]}}

An example of this props are:

preFormikKey = 'menus'

index = 0 // can be N

postFormikKey = 'name' // can be price or name

Interfaces

interface ComponentProps {    formikKey: string;    preFormikKey?: string;    index?: number;    postFormikKey?: string;}interface InitialState {    [key: string]: string | any[];}interface FormikPropsWrap {    formikProps: FormikProps<InitialState>;}

Ugly code

if (preFormikKey) {            if (index || index === 0) {                if (postFormikKey) {                    if (preFormikKey in formikProps.errors) {                        const errorMenus: any = formikProps.errors[preFormikKey];                        if (index in errorMenus) {                           // line below  object is posibly undefined                            const errorMenuIndex: any = formikProps.errors[preFormikKey][index];                            if (postFormikKey in errorMenuIndex) {                                // line below object is posibly undefined                                 //and "Element implicitly has an 'any' type because index expression is not of type 'number'" in postFormikKey                                errorMessage = formikProps.errors[preFormikKey][index][postFormikKey];                            }                        }                    }                    if (preFormikKey in formikProps.values) {                        const valuesMenus: any = formikProps.values[preFormikKey];                        if (index in valuesMenus) {                            const valuesMenuIndex: any = formikProps.values[preFormikKey][index];                            if (postFormikKey in valuesMenuIndex) {                                value = formikProps.values[preFormikKey][index][postFormikKey];                            }                        }                    }                    if (preFormikKey in formikProps.touched) {                        const touchedMenus: any = formikProps.touched[preFormikKey];                        if (index in touchedMenus) {                            const touchedMenuIndex: any = formikProps.touched[preFormikKey][index];                            if (postFormikKey in touchedMenuIndex) {                                touched = formikProps.touched[preFormikKey][index][postFormikKey];                            }                        }                    }                }            }        }
Viewing all 6215 articles
Browse latest View live


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