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

React Navigation v5 Disable Option Menu

$
0
0

I am trying to achieve an disabled (not hidden) specific option menu item from the sidebar (navigation drawer). I went over the official docs, but didn't find any answer how to achieve it. Did any one manage to do it via the DrawerItemList ?

Here is the code snippet:

<NavigationContainer linking={linking}><Drawer.Navigator          drawerStyle={{width: 0.85 * width}}          initialRouteName="Home"          drawerContentOptions={{            activeTintColor: 'gray',          }}          drawerContent={(props: DrawerContentComponentProps) => {            const {user} = this.props.userStore;            return <DrawerContent {...props} user={user} />;          }}><Drawer.Screen            name="Home"            component={Home}            options={{drawerLabel: 'Home', drawerIcon: HomeIcon}}          /><Drawer.Screen            name="Companies"            component={CompanyList}            options={{              drawerLabel: 'Companies',              drawerIcon: CompaniesIcon,            }}          /><Drawer.Screen            name="Members"            component={Profile}            options={{              drawerLabel: 'Members',              drawerIcon: MembersIcon,            }}          /><Drawer.Screen            name="Programs"            component={Profile}            options={{drawerLabel: 'Programs', drawerIcon: ProgramsIcon}}          /><Drawer.Screen            name="MyNetwork"            component={Profile}            options={{              drawerLabel: 'My Network',              drawerIcon: MyNetworkIcon,            }}          /><Drawer.Screen            name="Inbox"            component={Profile}            options={{drawerLabel: 'Inbox', drawerIcon: InboxIcon}}          /><Drawer.Screen            name="Holdings"            component={Profile}            options={{drawerLabel: 'Holdings', drawerIcon: HoldingsIcon}}          /><Drawer.Screen            name="Support"            component={Profile}            options={{              drawerLabel: 'Support',              drawerIcon: SupportIcon,            }}          /><Drawer.Screen name="Profile" component={Profile} /></Drawer.Navigator></NavigationContainer>

DrawerContent.tsx

interface DrawerProps extends DrawerContentComponentProps {  user: User | null;}function DrawerContent(props: DrawerProps): JSX.Element {  const secondaryText = '#61616A';  return (<Container><Content contentContainerStyle={styles.content}><DrawerContentScrollView          contentContainerStyle={{paddingTop: 36}}          {...props}><DrawerItemList            {...props}            itemStyle={{              marginStart: 0,              marginEnd: 0,              paddingStart: 36,            }}          /></DrawerContentScrollView></Content></Container>  );}export default DrawerContent;

Passing and Receiving data from Functional Components React-Native

$
0
0

I have 2 functions, one function has the data, another function will accept the data.

so I want to pass the entire transaction data from TransactionHistoryListItem into TransactionHistoryScreen function. I am having issues on how to pass and accept the data. Currently, my error is this.

The expected type comes from property 'transaction' which is declaredhere on type 'IntrinsicAttributes & { transaction: { id: number; title: string; data: { id: number; name:string; accountNumber: number; amount: string; type: string; }[]; };}'

  • TransactionHistoryListItem (which has the transaction data)
export default function TransactionHistoryListItem() {    const [transaction, setTransaction] = useState ([        {            id: 0,            title: 'Mon, 01 Aug',            data: [                {id: 1, name: 'Ores', accountNumber: 123456789, amount:'- MYR 20.00', type: 'out'},                {id: 2, name: 'RM 12', accountNumber: 987654321, amount:'+ MYR 12.00', type: 'in'},                {id: 3, name: 'GO Noodles', accountNumber: 123456789, amount:'- MYR 10.00', type: 'out'},                {id: 4, name: 'Notes', accountNumber: 123456789, amount:'- MYR 10.00', type: 'out'},            ]        },                {            id: 1,            title: 'Thu, 21 Jul',            data: [                {id: 5, name: 'Pulau ketam ytf', accountNumber: 123456789, amount:'- MYR 13.05', type: 'out'},                {id: 6, name: 'Notes', accountNumber: 123456789, amount:'+ MYR 20.00', type: 'in'},                {id: 7, name: 'Sephora', accountNumber: 918273645, amount:'- MYR 120.00', type: 'out'},                {id: 8, name: 'Dad', accountNumber: 123456789, amount:'+ MYR 200.00', type: 'in'},            ]        },               {            id: 2,            title: 'Sat,17 Jul',            data: [                {id: 9, name: 'Bill', accountNumber: 123456789, amount:'- MYR 20.00', type: 'out'},                {id: 10, name: 'Claim', accountNumber: 123456789, amount:'+ MYR 50.00', type: 'in'},            ]        },                {            id: 3,            title: 'Tue,15 Jul',            data: [                {id: 11, name: 'Food', accountNumber: 123456789, amount:'- MYR 20.00', type: 'out'},                {id: 12, name: 'Shoes', accountNumber: 123456789, amount:'- MYR 50.00', type: 'out'},                {id: 13, name: 'Ink', accountNumber: 123456789, amount:'- MYR 50.00', type: 'out'},                {id: 14, name: 'Claim', accountNumber: 123456789, amount:'+ MYR 500.00', type: 'in'},            ]        },        {            id:4,            title: 'Thu, 13 Jul',            data: [                {id: 15, name:'Zalora', accountNumber: 214365879, amount:'-230.00', type: 'out'},                {id: 16, name:'Nasi goreng', accountNumber: 324215678, amount:'-8.00', type:'out'},            ]        }    ]);    return <TransactionHistoryScreen transaction = {transaction} />}
  • TransactionHistoryScreen (will accept the transaction data)
export default function TransactionHistoryScreen({transaction}    :{transaction: { id: number; title: string; data: { id: number; name: string; accountNumber: number; amount: string; type: string}[];}} ) {    return(<View><Suspense fallback = {<View><Text style = {styles.lazy}>Loading...</Text>  <ActivityIndicator animating size = "small" color = '#CED0CE' hidesWhenStopped ={true}/></View>}><TransactionHistoryList/></Suspense></View>    )}

extend according to components inside it

$
0
0

In my containerTop, I am rendering a list inside TripOptionsSelectorthat hides towards the end.

I have tried adding marginBottom/paddingBottom to containerOptionsSelectorbut it makes no difference. I don't want to add a height to my because it can vary according to different phones.

How else can I simply extend the View such that the text doesn't hide?

export const MapScreen: React.FunctionComponent = () => {  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.containerTop}><BackArrow /><JourneyLocationsTextContainer /><View style={styles.containerOptionsSelector}><TripOptionsSelector /></View></View><View style={styles.containerMap}><MapContainer /><ButtonsContainer /></View></View></SafeAreaView>  );};const styles = StyleSheet.create({  safeAreaViewContainer: { flex: 1 },  container: {  flex: 1, backgroundColor: 'white'},  containerTop: { flex: 1, backgroundColor: '#323443' },  containerOptionsSelector: {    marginTop: moderateScale(15),    marginLeft: moderateScale(20),  },  containerMap: {     flex: 2  },});
export const TripOptionsSelector: React.FunctionComponent = () => {  return (<View style={styles.offerContainer}><Text style={styles.offerText}>Jetzt</Text><Text style={styles.offerText}>1 Person</Text><Text style={styles.offerText} >Filter</Text></View>  );};const styles = StyleSheet.create({  offerContainer: {    flexDirection: 'row',  },

enter image description here

Props declared as interface not available when navigating to a Component

$
0
0

I have Component wherein props are declared as an interface and that component takes in the type as that interface.

For eg ->

import React, { Component } from 'react'import { Text, View } from 'react-native' interface IDummy{    name:string;    age:number;}export default class Dummy extends Component<IDummy,any> {    constructor(props:IDummy){        super(props)        console.log('CHeck the props here ',props)    }    render() {        return (<View><Text> Just Text </Text></View>        )    }}

Now if I use that component as a part of other components such as

<Text>Something</Text><Dummy/>

The props name and age work fine.But when I want to navigate to that component,

navigation.navigate('Dummy')

the props mentioned in the interface are not available.Is there any way I could access them ???

React Native SyntaxError in node_modules/react-native/index.js: Unexpected token, expected "{" (13:7) on Android Build

$
0
0

I have initialized a react-native-project and converted it to use TypeScript. I also setup the project to compile to web, android, and ios. Webpack was installed to launch the web version. I got everything working on Web and iOS just fine but when I run yarn android and build to android I get a Syntax error in the Metro window and on the android simulator coming from the index.js file inside the react-native project under node_modules.

This is only happening on Android. I have installed a number of babel plugins and presets so I'm not sure why this index.js file is not working for Android but works correctly on iOS. Any help would be great. I have uploaded the project in a public repo.

I have the starter project available in a github repo so you can pull down my exact setup.https://github.com/hybridmindset/liveapp

I am running on a Mac OS version Catalina 10.15.4Node v14.0.0

Metro server window with Error

Android Simulator Window with Error

Problem with TS lib autocomplete/intellisense

$
0
0

in the project where i am working we have a component library that we use on various react native projects. Recently the team decided to rewrite this lib using typescript, we now finished this refactor, but the problem is that the VS Code autocomplete is not working with the lib components.

Our tsconfig.json file:

{"compilerOptions": {"allowJs": false,"esModuleInterop": true,"declaration": true,"jsx": "react-native","target": "ESNext","moduleResolution": "node","skipLibCheck": true,"module": "System","outFile": "index.ts","emitDeclarationOnly": true,"strictPropertyInitialization": false  }}

I have put the definition file (d.ts) that is being generated on the project root directory on types, at the package.json config file.

I've tried to generate this definition file inside a @types folder but it didn't work either.

I'm sorry, but i can't share too much from the projects since they're private.

Thank you all in advance.

Can I use a React hook directly as a prop in JSX?

$
0
0

I managed to get it with no warnings from TSLint. I will not be able to test it until several days since I'm heavily refactoring the app.

I never seen useCustomHook() passed directly in provider's value in tutorials or docs. It seems much more simple to write. Is it a bad practice, or what ?

import useCustomHook, {customHookInitialValues, UseCustomHookType} from './useCustomHook'export const Context = createContext<UseCustomHookType>({customHookInitialValues})export const ContextProvider = ({ children }: Props) =><Context.Provider value={useCustomHook()}>{children}</Context.Provider>

Visual Studio Code:[js] types can only be used in a .ts file

$
0
0

Is it possible to use .js files in a typescript project in vs code? I have clone a react-native project from a github repository and opened it in visual studio code. When I add a tsconfig.json in order to start using typescript,I get a long list of errors. For example here is a drawer.js file (with es6 features):

enter image description here

Here is my tsconfig.json file (If I remove this file then every thing works fine, no error reported) :

enter image description here


How to Improve performance for React Native geolocation running screen

$
0
0

Hi I'm currently trying to build a running app similar to the UnderArmor running app in React Native. The features work but after a couple of minutes of using the app on the simulator the computer starts to overheat and the app's performance significantly decreases, after a bit it no longer becomes responsive. Am I making too many calculations per frame? Thank for for your help

const { width, height } = Dimensions.get('window')const LATITUDE_DELTA = 0.007;const LONGITUDE_DELTA = 0.007;const LATITUDE = 37.78825;const LONGITUDE = -122.4324;var email = "";const RunMapScreen = () => {  const paperTheme = useTheme();  const [state, setState] = useState({    isActive: false,    close: true,    routeCoordinates: [],    distanceTravelled: 0,    prevLatLng: {},    latitude: LATITUDE,    longitude: LONGITUDE,    seconds: 0,    now: moment(),    then: moment(),    timeElapsed: "00:00:00",    startCounter: 0,    speedCounter: 1,    speed: 0,    averageSpeed: 0,    isModalVisible: false,    email: "grt",  });  const [isModalVisible, setModalVisible] = useState(false);  useEffect(() => {    this.watchID = navigator.geolocation.watchPosition((position) => {      const newLatLngs = { latitude: position.coords.latitude, longitude: position.coords.longitude }      const positionLatLngs = _.pick(position.coords, ['latitude', 'longitude']);      handleUpdates(position.coords.latitude, position.coords.longitude, newLatLngs, positionLatLngs, position.coords.speed);    });    return () => {      navigator.geolocation.clearWatch(watchID);    }  }, [state]);  const handleUpdates = (lat, long, newLatLngs, positionLatLngs, speedVal) => {    setState(state => ({ ...state, latitude: lat, longitude: long }));    if (state.isActive) {      setState(state => ({        ...state, routeCoordinates: state.routeCoordinates.concat(positionLatLngs),        distanceTravelled: state.distanceTravelled + calcDistance(newLatLngs),        prevLatLng: newLatLngs,        now: moment(),        timeElapsed: moment.utc(moment(state.now, "DD/MM/YYYY HH:mm:ss").diff(moment(state.then, "DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"),        speedCounter: state.speedCounter + 1,        speed: speedVal,        averageSpeed: ((state.averageSpeed * (state.speedCounter - 1) + state.speed) / state.speedCounter),      }));    }  };  const calcDistance = (newLatLng) => {    const prevLatLng = state.prevLatLng;    return (haversine(prevLatLng, newLatLng) || 0);  };  const openIsActive = () => {    var now;    if (!state.isActive && state.startCounter === 0) {      setState(state => ({        ...state,        timeElapsed: moment.duration(state.now.diff(state.then)),        then: moment(),        startCounter: 1      }));    } else if (state.isActive && state.startCounter === 1) {      now = { ...state.now };    } else if (!state.isActive && state.startCounter === 1) {      var then = { ...state.then };      var diff = -state.now.diff(now);      setState(state => ({ ...state, then: moment(then).add(diff) }));    }    setState(state => ({ ...state, isActive: !state.isActive }));  }  const toggleModal = () => {    setState(state => ({ ...state, isModalVisible: !state.isModalVisible }));  };  const getMapRegion = () => ({    latitude: state.latitude,    longitude: state.longitude,    latitudeDelta: LATITUDE_DELTA,    longitudeDelta: LONGITUDE_DELTA  });

What is module 53? [duplicate]

$
0
0

Hi javascript experts!

I am trying to run a react-native project in development mode on my iphone. I do not know which package introduced this issue. I use typescript (.ts, .tsx, and also .jsx) in parts of my project.

What is this module "53" that this error refers to?

Unhandled JS Exception: Requiring unknown module "53". If you are sure the module exists, try restarting Metro. You may also want to run `yarn` or `npm install`.loadModuleImplementation@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:226:31http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:27951:60loadModuleImplementation@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:271:14http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:27925:38loadModuleImplementation@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:271:14http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:27861:14loadModuleImplementation@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:271:14guardedLoadModule@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:163:47global code@http://192.168.1.8:8081/index.bundle?platform=ios&dev=true&minify=false:154118:4loadModuleImplementation    index.bundle?platform=ios&dev=true&minify=false:226:31loadModuleImplementation    index.bundle?platform=ios&dev=true&minify=false:271:14loadModuleImplementation    index.bundle?platform=ios&dev=true&minify=false:271:14loadModuleImplementation    index.bundle?platform=ios&dev=true&minify=false:271:14guardedLoadModule    index.bundle?platform=ios&dev=true&minify=false:163:47global code    index.bundle?platform=ios&dev=true&minify=false:154118:4

module 53 is unknown, error on iOS react-native app

How to set all react-redux store with typescript?

$
0
0

When you use react-redux, what do you have to do? To set store, actions, reducers and use useselector and usedispatch? Is there anything else? And where typescript helps you with that?

Can I find out the real cause of this error? (React Native)

$
0
0

First I apologize for my english. I have been working on react native applications for 4 months. But sometimes I get this error and don't mind.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method,in CustomerDetailScreen (at SceneView.tsx:123)

This is because when I click the button, I open a screen and when the screen is not fully loaded I press the back button. How can I resolve this warning? I'll show you some sample code examples.

I hope I could explain. Can you help me with this topic? I want to fully understand the logic. I've read something called AbortController in some articles but I don't know exactly.

constructor(props) {    super(props);    this._isMounted = false;    this.state = {        id: props.route.params.id,        username: '',        token: null,        cityId: 1,        townId: 1,        cityData: [],        townData: [],        selectedIndex: 0,        selectedCity: new IndexPath(0),        selectedTown: new IndexPath(0),    }}componentDidMount() {    this._isMounted = true;    this._isMounted && this._getToken();}componentWillUnmount() {    this._isMounted = false;}_getToken = async () => {            try {      const username = await AsyncStorage.getItem('username');      const token = await AsyncStorage.getItem('token');      if(token === null) {        await AsyncStorage.removeItem('token');      }else {        this.setState({ username: username, token: token });        this._isMounted && this.loadCustomerDetail();      }    } catch (error) {        console.log(error);    }};loadCustomerDetail() {    try {        const { username, token } = this.state;        if(token) {            const { id } = this.state;            var credentials = Base64.btoa(username +':'+ token);            var URL         = `https://portal.xxxxxx.com/api/v1/Customer/${id}`;            axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})            .then(this.dataSuccess.bind(this))            .catch(this.dataFail.bind(this));                        }    }catch (err) {        console.log(err);    }};dataSuccess(response) {    this.setState({        isLoading: false,        cityId: response.data.cityId,        townId: response.data.townId    }, () => {        this.getCities();    });}getCities() {    const { username, token, cityId } = this.state;    let credentials = Base64.btoa(username +':'+ token);    axios.get('https://portal.xxxxx.com/api/v1/Cities', { headers : { 'Espo-Authorization' : credentials }})    .then((response) => {            response.data.list.sort(function(a, b) {                return Number(a.id) > Number(b.id);            });            this.setState({cityData: response.data.list}, () => {                this.setState({ selectedCity: new IndexPath(this.state.cityData[cityId-1].id - 1) });                this.getTowns(this.state.cityData[cityId-1].id);            });        }).catch((error) => {            console.log(error);        });}getTowns(cityId) {    this.setState({ townLoading: true });    const { username, token } = this.state;    let credentials = Base64.btoa(username +':'+ token);    axios.get(`https://portal.xxxxx.com/api/v1/Towns/action/TownList?cityId=${cityId}`, { headers : { 'Espo-Authorization' : credentials }})      .then((response) => {            this.setState({ townData: response.data, townLoading: false }, () => {                for (const [key, value] of Object.entries(this.state.townData)) {                    if(value.id === this.state.townId) {                        this.setState({ selectedTown: new IndexPath(key) })                    }                }            });                        }).catch((error) => {            console.log(error);        });}

typescript react-native : async function return res to late

$
0
0

I trying to search on database some information, and update my state after get the response.

for example :

export const barcodeOnitems = async (barcode: string) => {    db.transaction((tx) => {        tx.executeSql('SELECT * FROM items where barcode = ?',            [barcode],            (txObj, resultSet) => {                if(resultSet.rows.length){                    return true;                }else{                    return false;                }            },            (err) => {                console.log(err);                return false;            }        );    });};
import { barcodeOnitems } from '../tools/database'[...]const [result, setResult] = useState(null);[...]barcodeOnitems(val).then(async (res) => {    setResult(res)});

But I'm almost sure it's because setResult(res) work before the return of barcodeOnitems.

So I try to use async function but I don't understand why this doesn't work.

Thanks for answers

EDIT :what about promise ?

if(resultSet.rows.length){    return new Promise((resolve) => {        resolve(true)    });    }else{        return new Promise((resolve) => {            resolve(false)    });}

Is there a method to find the location of a ReactNode on screen?

$
0
0

Is there a way to get the location (such as left, right, top, bottom) for a ReactNode? I can't seem to find anything.

I'm looking for something very similar to the getBoundingClientRect() function.

Arguments inside "onChange" its no compatble with "NativeSyntheticEvent"

$
0
0

I am new with react native and when i try do this

<TextInput          style={styles.input}          onChange={(text) => setPontoValue(text)}        />

i receive this error

TS2345: Argument of type 'NativeSyntheticEvent<TextInputChangeEventData>' is not assignable to parameter of type 'SetStateAction<undefined>'.   Type 'NativeSyntheticEvent<TextInputChangeEventData>' provides no match for the signature '(prevState: undefined): undefined'.

all code is below

import React, { useState } from 'react'import {  TextInput,  TouchableOpacity,  StyleSheet,  SafeAreaView,  Text,  View, Button,} from 'react-native'export default function App() {  const [pontoValue, setPontoValue] = useState()  const [dataValue, setDataValue] = useState()  return (<SafeAreaView style={styles.container}><View style={styles.repositoryContainer}><TextInput          style={styles.input}          onChange={(text) => setPontoValue(text)}        /><TextInput          style={styles.input}          value={dataValue}        /><TouchableOpacity><Button            title="Calcular"            onPress={teste}>Converter</Button></TouchableOpacity></View></SafeAreaView>  )  function teste() {    if (pontoValue) {      setDataValue(pontoValue.replace(/[ .]+/g, ''))    }  }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    alignContent: 'center',    backgroundColor: '#7199c1',  },  repositoryContainer: {    marginBottom: 15,    marginHorizontal: 15,    backgroundColor: '#fff',    padding: 20,  },  input: {    height: 40,    padding: 5,    borderColor: 'gray',    borderWidth: 1,  },  buttonText: {    marginVertical: 11,    fontSize: 14,    fontWeight: 'bold',    color: '#fff',    backgroundColor: '#7159c1',    padding: 15,  },})

move text in center for all lines [duplicate]

$
0
0

I render such an item in a FlatList. When the name is too long, it extends to the next line, which is okay but I want that it should still be in the center. The second line should also be positioned in the center. For example, Ross should also approximately come under Vom. Is that possible?

export const FriendEntry: React.FunctionComponent<FriendEntryProps> = ({  friend,  currentUserId,}) => {  return (<View style={styles.item}><TouchableOpacity><Thumbnail          style={styles.thumbnail}          source={{            uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',          }} /></TouchableOpacity><View style={styles.nameContainer}><Text style={styles.userName}>{userName}</Text></View><View style={styles.deleteButtonContainer}><Button          rounded          style={styles.deleteButton}<Icon name="trash-o" size={moderateScale(20)} color="black" /></Button></View></View>  );};export const styles = StyleSheet.create({  item: {    backgroundColor: 'white',    borderRadius: moderateScale(20),    padding: moderateScale(20),    marginVertical: moderateScale(8),    marginHorizontal: 16,    height: moderateScale(110),    justifyContent: 'space-between',    flexDirection: 'row',  },  userName: {    paddingRight: 55,    paddingLeft: 10,    paddingTop: 20,  },  deleteButton: {    backgroundColor: '#31C283',    width: moderateScale(45),    justifyContent: 'center',  },  deleteButtonContainer: {    paddingTop: 12,    marginRight: 2,  },  thumbnail: {    height: 85,    width: 85,    marginLeft: 2,    paddingRight: 0,    position: 'relative',  },  nameContainer: {    flex: 1,    alignItems: 'center',    textAlign: 'center'  },});

enter image description here

add background color to thumbnail

$
0
0

I am using a thumbnail where the cross is transparent and takes the background color of the main container. I want the cross to be white.

export const FriendDetailsScreen: React.FunctionComponent = () => {  const navigation = useNavigation();  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.iconsContainer}><TouchableOpacity          style={styles.cross}><Thumbnail            source={{              uri:'https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-512.png',            }}          /></TouchableOpacity></View></View></SafeAreaView>  );};export const styles = StyleSheet.create({  safeAreaViewContainer: {    flex: 1,  },  container: {    backgroundColor: '#323443',    flex: 1,  },cross: {    paddingTop: moderateScale(30),    paddingLeft: moderateScale(20),    zIndex: 100,  },});

If I add a background color to cross or the TouchableOpacity a block of white appears which goes beyond the thumbnail. How else can I achieve this?

Thumbnail:https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-512.png

If I add a style to the thumbnail itself:

  thumbnail:{    backgroundColor: 'white',  }

I get this, and this is not what I want. I don't want the border outline.enter image description here

Remove border in Native Base Thumbnail

$
0
0

I am using a thumbnail where the cross is transparent so to give it a white background color, I added it in its style. However, a white border line also appears. How can I remove this?

export const Screen: React.FunctionComponent = () => {  return (<SafeAreaView style={styles.safeAreaViewContainer}><View style={styles.container}><View style={styles.iconsContainer}><TouchableOpacity          style={styles.cross}><Thumbnail  style={styles.thumbnail}            source={{              uri:'https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-512.png',            }}          /></TouchableOpacity></View></View></SafeAreaView>  );};export const styles = StyleSheet.create({  safeAreaViewContainer: {    flex: 1,  },  container: {    backgroundColor: '#323443',    flex: 1,  },cross: {    paddingTop: moderateScale(30),    paddingLeft: moderateScale(20),    zIndex: 100,  },  thumbnail:{    backgroundColor: 'white',  }});

enter image description here

Expo, TypeScript, and External Imports over Multiple TypeScript Projects

$
0
0

I've just stumbled upon the fact that I can only import enums and interfaces from an external TypeScript project into my React Native (with TypeScript) project.

In fact, I think that as long as what I want to import comes from an export default module it can work. (So far trying to import other things like export const and export function don't work either.) I feel this is a TypeScript issue and not particular to React Native or Expo frameworks.

What I'm trying to accomplish is as follows:

I've offloaded my entire Redux state tree, actions, and reducers to a separate repository so I can share the code between two frontends (web and react-native). In my React Native and web projects, I've been importing interfaces and enums from a third project all the while, which is my API. Those imports (as I mentioned, so far are only enums and interfaces) work just fine.

But when I try to import the store object, for example, in the web or react native projects, i.e.

import { store } from '../../my-redux-repository/store/index'

It always fails with:

Unable to resolve "../../my-redux-repository/store/index" from "where/im/trying/to/import/it"

Could it be perhaps because the standard store file looks like this in Redux:

export const rootReducer = combineReducers({  foo: fooReducer,  bar: barReducer,<<[more reducers here...]>>});export type RootState = ReturnType<typeof rootReducer>;export const store = createStore(  rootReducer);

Where there is no default export but just a variety of exports?

I tried leveraging Project References from TypeScript. But that doesn't seem to help. I still get the same Unable to resolve... error.

Does anyone have experience with importing more than just enums and interfaces from an external project? TypeScript's official docs don't go too far into details.


EDIT:

As a sanity check, I've just tried refactoring my store file to:

const store = createStore(  rootReducer);export default store;

but this also doesn't work. So the end result is that I'm only able to import default enum and default interface items successfully. Otherwise, I'm lost as to what is going wrong.


SECOND EDIT:

It seems that in fact, this is either a React Native or Expo issue, as I can import everything from the redux project just fine (store, action functions, types, etc.) in my Gatsby project (which uses Webpack behind the scenes) - no projects or namespaces required! Just import as expected and it works as expected.

Memory leak when using custom text in React Native

$
0
0

I'm working on my React Native project and I'm getting the famous "Can't perform a React state update on an unmounted component" sometimes when I'm using my custom text component. This is quite weird, because I'm following the same steps as the docs. Here's the component:

import React, { FunctionComponent } from "react";import { Text, TextStyle } from "react-native";import { AppLoading } from "expo";import {  useFonts,  Montserrat_500Medium,  Montserrat_800ExtraBold,} from "@expo-google-fonts/montserrat";import { colors } from "./ConstantStyles";type CustomTextProps = {  style?: TextStyle | TextStyle[];  variant?: string;};const PrimaryText: FunctionComponent<CustomTextProps> = ({  children,  style,  variant,}) => {  let [fontsLoaded] = useFonts({    Montserrat_500Medium,    Montserrat_800ExtraBold,  });  const passedStyles = Array.isArray(style)    ? Object.assign({}, ...style)    : style;  if (!fontsLoaded) {    return <AppLoading />;  } else {    return (<Text        style={[          {            fontFamily:              variant === "bold"                ? "Montserrat_800ExtraBold"                : "Montserrat_500Medium",          },          { ...passedStyles },        ]}>        {children}</Text>    );  }};export default PrimaryText;

What am I doing wrong?

Viewing all 6214 articles
Browse latest View live


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