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

Pass style as props in react component

$
0
0

I created a event-box component in react. What I want is whenever is it called, I passed color values as props which later get used to set its border. Currently, I set two hardcoded class names and passed them as props with the component. Is there any other way to do so as I won't able to add all the color class names in my stylesheet.

Component code

import React from 'react';class EventBox extends React.Component{    constructor(props)    {        super(props);        this.state={        }    }    render()    {        const style={            marginBottom:'0px'        }        const list={            display:'inline-flex',            width:'100%',            marginBottom:'10px'        }        const listItem={            flex:'1',            display:'flex'        }        return(<div className={this.props.class}><ul className="list list-inline" style={list}><li className="list-inline-item color-golden" style={listItem}>1 March 2020</li><li className="list-inline-item color-red flex flex-end" style={listItem}>200 People Interested</li></ul><h3 className="sub-heading roboto">Title</h3><p className="paragraph roboto" style={style}>Saket, New Delhi</p><p className="paragraph roboto" style={style}>Time: 05:00 P.M - 06:30 P.M</p></div>        )    }}export default EventBox;
<EventBox class="col-md-12 event-box-container red-border" /><EventBox class="col-md-12 event-box-container green-border" />

CSS

.event-box-container.red-border{    border-top: 8px solid red;}.event-box-container.green-border{    border-top: 8px solid green;}

VSCode react native no import errors detected in code

$
0
0

I have been using vscode for couple of years but recently with version 1.45 i don't see any errors detected while i code . For example , it does not validate whether the import statement is valid nor the modules inside is valid or not . Earlier it used to clearly mark it in red if a module is not found in the import statement but still declared .

Vscode treats unknown variables as "any" and does not show any error unless i run it in the simulator.

Secondly, whenever i type an object if an import statement is found i used to see the option highlighted and now i don't see that either.

Any clue on why this behavior in vscode?.

How to use AWS Amplify in React Native with Typescript Project?

$
0
0

I'm trying to add Amplify Authentication in my react native project which uses typescript.There is a package given in amplify documentation 'aws-amplify-react-native' which is used as a middleware to authenticate our application.But this package is only supported in projects which are based on javascript.For Typescript it shows an error like

Could not find a declaration file for module 'aws-amplify-react-native'.Try `npm install @types/aws-amplify-react-native` if it exists or add a new declaration (.d.ts) file containing `declare module 'aws-amplify-react-native';`

There is no package available like '@types/aws-amplify-react-native'

So anyone can help me out of this?

How to define onClick event in react properly?

$
0
0

I tried to set an onClick event to open a flexbox in react using tsx. The button and the flexbox is shown properly but vscode shows a problem with the onClick event. I cant figure out whats wrong but maybe you can. I am new to the field and tried some ideas from the stack community but it didnt work for me.

The console tells me I have to assign 'string' but it doesnt work either.

//Function to change visibility of the flexBoxdocument.getElementById("OpenProfiles")   .addEventListener("click", ProfilesOpn);function ProfilesOpn () {    var a = document.querySelectorAll(".ProfilesOpen")[0];    var b = document.querySelectorAll(".ProfilesClose")[0];    a.style.visibility = "hidden"    b.style.visibility = "visible";}//the button code inside the flexbox <div className={"Profiles"}><div className={"Profile1"}><div className={"Profile1P"}></div><h3 className={"ProfileH3"}>Profile1</h3>     </div><div className={"Profile2"}><div className={"Profile2P"}></div><h3 className={"ProfileH3"}>Profile2</h3>     </div><div className={"Profile3"}><div className={"Profile3P"}></div><h3 className={"ProfileH3"}>Profile3</h3>     </div><div className={"Profile4"}><div className={"Profile4P"}></div><h3 className={"ProfileH3"}>Profile4</h3>     </div><h3 className={"EndCoPro"}>Are you missing any profiles?</h3><button id="OpenProfiles" onClick="return(ProfilesOpn());"><div className={"ProfilesOpen"}><img src={ProfilesOpen} alt="Open Profiles"/></div></button></div>//the code in sass for the styling .Profiles {  position: absolute;  display: flex;  left: 0px;  bottom: 0px;  width: 300px;  height: 900px;  flex-direction: column;  justify-content: flex-start;  align-items: space-between;  background-color: #292929;  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);  border-top-right-radius: 25px;  border-bottom-right-radius: 25px;  visibility: hidden;}

What is the Typescript Typing for scrollXAnimated in React Native?

$
0
0

What is the Typescript Typing for scrollXAnimated in React Native? I've looked through the docs and haven't seen anything for this.

TypeScript Type:

// TypeScript Type: Propsinterface Props {  scrollXAnimated: any, // WHAT CAN I ADD INSTEAD OF ANY?  data: any,};

The Code:

  const translateY = props.scrollXAnimated.interpolate({    inputRange: [-1, 0, 1],    outputRange: [HEADER_HEIGHT, 0, -HEADER_HEIGHT],  });

Warning weird: is declared but its value is never read

$
0
0

This is my code:'Skeleton' is declared but its value is never read.

import React from 'react';import {    FlatList, View, StyleSheet} from 'react-native';// But warning here import { Skeleton, Colors } from '@momo-platform/component-kits';const SkeletonLoadingChat = () => {    const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];    return (<FlatList            style={{ padding: 15 }}            data={data}            ListHeaderComponent={() => {                return (<View style={styles.headerSkelation}><View style={styles.avataSkelation} /><View style={styles.lineSkelation} /></View>                );            }}            renderItem={({ item, index }) => {                return (                    // I used Skeleton here<Skeleton.Custom                        left={<Skeleton.Media size={52} />}                        style={styles.skeletionItem}><Skeleton.Line style={styles.width_1_9} /><Skeleton.Line style={styles.width_80} /></Skeleton.Custom>                );            }}        />    );}

enter image description here

I used Skeleton but it still shows a warningInterface Skeleton

export interface Skeleton extends SkeletonProps {  Line?: React.ReactElement,  Media?: React.ReactElement,  Custom?: React.ReactElement,}

If I remove import Skeleton it shows errorenter image description here

How to add button on header in nested stack navigation in react native

$
0
0

I am trying to add a button on right side of a header in one of the stack navigation in my app but the problem is its not working.

Here is my code.I don't know why this is not working

App.tsx

<AppStack.Screen            options={{              headerShown: false,            }}            name="MyProfile"            component={TabNavigation}          /><AppStack.Screen            name="CommunityStack"            component={CommunityStack}          />

CommunityHub.tsx

const CommunityStack = () => {  return (<Stack.Navigator screenOptions={({ navigation }) => ({        title: "Community Hub",        headerRight: () => {          return (<Box marginHorizontal="s"><RoundedBorderButton                label="For Members"                onPress={() => navigation.navigate("Register")}              /></Box>          );        },      })}><Stack.Screen name="CommunityHub" component={CommunityHub} /><Stack.Screen name="KarawarDetail" component={KarawarDetail} /><Stack.Screen name="CommunityMember" component={CommunityMember} /></Stack.Navigator>  );};

React native user tags inside text input

$
0
0

I can't seem to properly figure out how to have formatted user tags that are editable inside of a text input.

For example:

const stateString = "{{ userId:1 }} is feeling great.";

To display a formatted user tag, I take that value, run it through a function, and it outputs "John is feeling great.", where John has a visible background color.

My problem is that on the next onChange trigger of my TextInput, e.nativeEvent.text is "John is feeling great." without any of the formatting.

If I feed that back to the TextInput component directly, I will lose the formatting as it will no longer have {{ userId: 1 }}.

My only option is to take stateString and compare it to e.nativeEvent.text, see what changed, and manually re-inject the user tags in.

The problem with that is that it's complicated (the change can be an added character, removed character, or removed multiple characters), and the fact that you can have John is with John coming from {{ userId:1 }} is with {{ userId:2 }}. Two different people, same first name.

The problem is that I need {{ userId:1 }} to send to the server, so it knows which users are mentioned in the comment.

Any ideas would be appreciated!


Prevent Child Rerendering if Parent is Rerendered Using Hooks

$
0
0

My bestSellerDummy data doesn't change, so I'd like to prevent the same Product child to be rerendered if parent rerenders. I have tried using useMemo in parent and React.memo in child but no luck, it's still showing log 'Rendering Product component..' every time parent rerenders. What am I missing here? Please advice.

Note: Parent is expected to be rerendered every time I call addToCart function (of CartContext) in a Product component.

Edit:I'm using CartContext, maybe related to this, I'm not sure. Here is the sandbox: https://codesandbox.io/s/dazzling-moore-po1c6?file=/src/App.js

Home.tsx

const [bestSellerDummy] = useState(  [...new Array(5)].map((item, key) => ({    id: key,    imageUri:'https://1.jpg',    name: 'My Dummy 1',    price: 25,  })),);const bestSellers = useMemo(() => {  return bestSellerDummy.map((productDummy, key) => {    return (<Product key={key} product={productDummy} />    );  });}, [bestSellerDummy]);return (  ...  {bestSellers}  ...)

Product.tsx

const Product: FunctionComponent<IProductProps> = (  productProps,) => {  ...  console.log('Rendering Product component..');  ...}export default React.memo(Product);

Property 'propTypes' does not exist on type 'typeof TextInput'

$
0
0

I am creating a react-native component using Typescript for the first time. And I get this following error in line 51: Property 'propTypes' does not exist on type 'typeof TextInput

Similar topics didn't help me. Does someone have an idea? Thanks

import React from "react";import { View, TextInput, StyleSheet, Text } from "react-native";import PropTypes from "prop-types";export type InputProps = {    label: any;    inputStyle: any;    containerStyle: any;    touched: any;    error: any;};const Input = ({  label,  inputStyle,  containerStyle,  touched,  error,  ...props}: Partial <InputProps>) => {  return (<View style={containerStyle}><Text>{label}</Text><TextInput style={inputStyle} {...props} /><Text style={styles.errorInput}>{touched && error}</Text></View>  );};const styles = StyleSheet.create({  containerStyle: {    marginVertical: 5,  },  input: {    borderBottomWidth: 1,    minHeight: 40,    padding: 10,  },  errorInput: { color: "red", fontSize: 12 },});const stylePropsType = PropTypes.oneOfType([  PropTypes.arrayOf(PropTypes.object),  PropTypes.object,]);Input.propTypes = {  inputStyle: stylePropsType,  containerStyle: stylePropsType,  ...TextInput.propTypes, // I have an error: "Property 'propTypes' does not exist on type 'typeof TextInput'.ts(2339)"};Input.defaultProps = {  inputStyle: styles.input,  containerStyle: styles.containerStyle,  touched: false,  error: null,};export default Input;

React Native TypeScript Images & Static Assets

$
0
0

I was following along in the tutorial that Microsoft put out on how to convert your ReactNative project to TypeScript.

Everything worked great until I reached the point where I needed to include images in my project. Obviously tsc doesn't pack up images into the outdir, so my question is how are people currently using images or other static assets when using ReactNative with TypeScript?

How do I configure absolute paths for imports in TypeScript based React Native apps?

$
0
0

In order to avoid '../../../../' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instead.

It is important that the configuration also supports Jest unit tests.

I created the app using npx react-native init MyTestApp --template typescript

React Native version: 0.60.5

What is the exact configuration I would need to achieve this?

How can i sorting combobox items on React with Typescript?

$
0
0

I have a project and in project there is a year combobox. I will the year sorting(asc to desc or desc to asc).

enter image description here

I have a form utils and I call the utils in a component.

Ensure that nested fields where the path is defined by a variable trigger React.useMemo update when added to the dependency array

$
0
0

I use TypeScript 4 and React 17

I had this code in a custom hook:

  const myValue = useMemo((): string[] => {    if (someCondition) {      return (myMap?.field && myMap.field.[subfieldId]) || null    } else {      ...    }  }, [filter, filterIsValid, myMap.field.[subfieldId]])

ESlint complained that myMap.field.[subfieldId] had to be moved in a variable to be checked progammatically.

So I changed to this:

  const currentData: string[] | null = (myMap?.field && myMap.field.[subfieldId]) || null  const myValue = useMemo((): string[] => {    if (someCondition) {      return currentData    } else {      ...    }  }, [filter, filterIsValid, currentData])

I'm not sure that letting the variable in the upper scope, being recalculated at each rendering is a good practice, I'm even worried that an infinite loop could be created.

ESLInt suggest me to to this instead, that is much more simple:

  const myValue = useMemo((): string[] => {    if (someCondition) {      return (myMap?.field && myMap.field.[subfieldId]) || null    } else {      ...    }  }, [filter, filterIsValid, myMap.field])

Will myMap.field be enought for React to find out that myMap.field[subfieldId] change? I guess it shall be. Indeed, React will not know what changed if I only put myMap, because the object reference itself does not change, but when comparing the previous and the new myMap.field, React check all the sub-fields. Does it?

React Hooks - Invalid Hook Call

$
0
0

I am getting an error

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:1. You might have mismatching versions of React and the renderer (such as React DOM)2. You might be breaking the Rules of Hooks3. You might have more than one copy of React in the same app

This is my hook useParking:

import { Strings } from "..";import { get } from "../HTTPProvider";import { Lot } from ".";import { Moment } from "moment";import L from "leaflet";interface ApiResponse {  id: string;  fields: Lot;  createdTime: Moment | string;}const { apiUrl, apiKey } = Strings;const [error, setError] = useState(false);const getParkingLots = (setParkingLots: (l: Lot[]) => void) => {  get<{ records: ApiResponse[] }>(`${apiUrl}Parking%20Lots`, { apiKey })    .then((response) => {      console.log(response);      const data: Lot[] = [];      response.data.records.forEach((record) => {        const lat = record.fields.latitude;        const lon = record.fields.longitude;        if (lat && lon) record.fields.coordinates = L.latLng([lat, lon]);        data.push(record.fields);      });      setParkingLots(data);    })    .catch((error) => setError(error));  console.log(error);};export const useParkingLot = (): Lot[] => {  const [parkingLots, setParkingLots] = useState<Lot[]>([]);  useEffect(() => {    getParkingLots(setParkingLots);  }, [parkingLots]);  return parkingLots;};

I am trying to use the hook in my MainTabs component here:

import {  IonTabs,  IonTabBar,  IonTabButton,  IonIcon,  IonLabel,  IonRouterOutlet,} from "@ionic/react";import { map, business, calendarOutline, carOutline } from "ionicons/icons";import { Route, Redirect } from "react-router";import { CampusMap, Events, Buildings, ParkingLots } from "../../pages";import { useFakeEvent } from "../../DataProviders";import { useBuilding } from "../../DataProviders";import { useParkingLot } from "../../DataProviders";export const MainTabs: React.FC = () => {  const buildings = useBuilding();  const parkingLots = useParkingLot();  const [events, setEvents] = useState(useFakeEvent());  const [showName, setShowName] = useState(true);  const toggleName = () => {    console.log("resetName called");    setShowName(false);    return setTimeout(() => {      setShowName(true);    });  };  return (<IonTabs><IonRouterOutlet><Route path="/:tab(Events)" render={() => <Events />} exact={true} /><Route          path="/:tab(Map)"          render={() => (<CampusMap              buildings={buildings}              showName={showName}              parkingLots={parkingLots}              events={events}            />          )}          exact={true}        /><Route          path="/:tab(BuildingList)"          render={() => <Buildings buildings={buildings} />}          exact={true}        /><Route          path="/:tab(ParkingLotList)"          render={() => <ParkingLots parkingLots={parkingLots} />}          exact={true}        /><Route exact path="/" render={() => <Redirect to="/Map" />} /></IonRouterOutlet><IonTabBar slot="bottom"><IonTabButton tab="Map" href="/Map" onClick={toggleName}><IonIcon icon={map} /><IonLabel>Map</IonLabel></IonTabButton><IonTabButton tab="BuildingList" href="/BuildingList"><IonIcon icon={business} /><IonLabel>Buildings</IonLabel></IonTabButton><IonTabButton tab="Events" href="/Events"><IonIcon icon={calendarOutline} /><IonLabel>Events</IonLabel></IonTabButton><IonTabButton tab="ParkingList" href="/ParkingLotList"><IonIcon icon={carOutline} /><IonLabel>Parking Lots</IonLabel></IonTabButton></IonTabBar></IonTabs>  );};

I have checked my code against the Rules of Hook documentation and it doesn't seem like I am breaking any. I have also checked my dependencies and they all check out. So I'm not sure why I'm getting the error. Can anyone see what I am doing wrong here?


Liferay React application and Typescript support

$
0
0

I'm using Liferay 7.2 and I have created react application using js-generator. By defaults it creating js files like index.js, App.js. I want typescript(.ts, .tsx) support in my Liferay react application. How can I? Please suggest the way to make Liferay react application supporting typescript.

I have gone through the below links and tried in my application as well :

  1. https://create-react-app.dev/docs/adding-typescript/
  2. https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

But above solutions not worked in case of Liferay react application.

Which version of React native started support for typescript?

$
0
0

We can create classes in typescript in react native now. But I want to know from which version of react native, typescript is supported.From official react native document (https://reactnative.dev/docs/0.60/typescript) I can see typescript reference for first time in React-Native V0.60.My doubt, is typescript supported in lower versions? like in React-native version less then 0.60?

React native error on ref scrollview, but working

$
0
0

I need to scroll to bottom of flatlist, so I use:

const scrollViewRef = useRef();//my scroll view<ScrollView    ref={scrollViewRef}    onContentSizeChange={() => {        scrollViewRef.current.scrollToEnd({ animated: true });    }}

but I got these errors:

enter image description here

The first one is:

No overload matches this call.  Overload 1 of 2, '(props: Readonly<ScrollViewProps>): ScrollView', gave the following error.    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.        Types of property 'current' are incompatible.          Type 'undefined' is not assignable to type 'ScrollView | null'.  Overload 2 of 2, '(props: ScrollViewProps, context?: any): ScrollView', gave the following error.    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.ts(2769)index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'

the second one is:

Object is possibly 'undefined'.

Any suggestions?

Check with TS that both optional params either passed or undefined

$
0
0

I'm writing an app with React native and Typescript and I have a question.

Let's image we have a simple component with three properties, one reqired and two optional:

interface Props {  requiredProp: string;  optionalPropA: boolean;  optionalPropB: Function;}

In my app logic either both optional properties have to be passed or none of them and I'm wondering how can I check that with TS?

I can think of only two ways how I can archieve that:

  1. Without using TS just simply check my condition with if somewhere before return
  2. Combine two optional properties into one. Make an object with two keys (one for each property) and make a TS type that will make sure that either both or none of them exists

Some examples:

// Should be good because all params were passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropA={true}  optionalPropB={() => {}}/>
// Should be good because only required param was passed<SimpleComponent  requiredProp={'Hello world'}/>
// Should complain that optionalPropB wasn't passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropA={true}/>
// Should complain that optionalPropA wasn't passed<SimpleComponent  requiredProp={'Hello world'}  optionalPropB={() => {}}/>

React Native TypeScript TextInput not working

$
0
0

I am trying to learn react native by doing a basic application. I followed many tutorials available online and made the following class for a login screen:

import React, { Component } from "react";import { View, StyleSheet, TextInput, Button, Alert, TouchableHighlight, Text } from "react-native";import { styles } from "../styles/CommonStyles";class LoginScreen extends Component {    constructor(props: Readonly<{}>) {        super(props)    }    state = {        email: ''    }    static navigationOptions = {        title: 'Login',        header: null    }    render() {        const { navigate } = this.props.navigation        return (<View style={styles.container}><TextInput                style={loginStyles.emailInput}                multiline={false}                autoCorrect={false}                autoCapitalize='none'                keyboardType='email-address'                value={this.state.email}                onChangeText={(text) => this.handleEmail(text)}                placeholder='Enter Email'/><TouchableHighlight                style={loginStyles.buttonGenerateOTP}                onPress={this.onGenerateOTP}><Text                    style={loginStyles.textGenerateOTP}>GENERATE OTP</Text></TouchableHighlight></View>        )    }    handleEmail(text: string) {        console.log('Email: '+ text)        this.setState({ email: text })        console.log('State Email: '+ this.state.email)    }    onGenerateOTP() {        Alert.alert('Email Entered',            this.state.email,            [                { text: 'OK', style: 'cancel' }            ],            { cancelable: false }        )    }}export default LoginScreenconst loginStyles = StyleSheet.create({    emailInput: {        fontSize: 15,        backgroundColor: '#ECECEC',        borderColor: '#999999',        borderRadius: 4,        borderWidth: 0.5,        alignSelf: 'stretch',        textAlign: 'center',        margin: 10,      },      buttonGenerateOTP: {          backgroundColor: '#008CBA',          borderRadius: 4,          alignSelf: 'stretch',          justifyContent: 'center',          alignItems: 'center',          margin: 10,          padding: 10,    },    textGenerateOTP: {        fontSize: 20,        color: '#FFFFFF',    },})

It only contains an input and a button, on which an alert should be shown with the entered email. But when I click the button, I am getting the following error:

undefined is not an object (evaluating 'this.state.email')onGenerateOTPLoginScreen.tsx:43:8...

I am pretty new to react native and typescript, but looking at the code, I couldn't figure out any issues. What is it that I am doing wrong here?

EDITThe log in handleEmail(text) function is actually printing the state, although with the previous value of text(ie, when I enter QWERT, it will print QWER, and when I enter QWERTY, it will print QWERT), but the text param is logging correctly

Viewing all 6213 articles
Browse latest View live


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