Press the text in a React Native TypeScript component to trigger a render

I am a newcomer to React Native and TypeScript, and I am struggling to figure out how to display something on the page of my app after a button is pressed.

Below is the function I'm using:

 const getRandomNumber = () ={
        const number = Math.floor(Math.random()*5000 + 1)
        alert(number)
        return <Text>{number}</Text>
        
    }

Here is where I am calling the function:

return(
        <View style={{flex: 1, justifyContent: "center", margin: 8}}>
        <Text>Random number</Text>
        <Button
         title="Press me"
         onPress={() => getRandomNumber()}
         color="#32a852"
        />
        </View>
    )

Answer №1

A click handler cannot be used for returning values.

It is recommended to utilize useState in order to assign a random number.

const [num, setNum] = React.useState(0);

 const generateRandomNumber = () =>{
        const randomNumber = Math.floor(Math.random()*10000 + 1)
        
        alert(randomNumber)
        
        setNum(randomNumber);
    }

return(
        <View style={{flex: 1, justifyContent: "center", margin: 8}}>
        <Text>Random Number:</Text>
        <Button
         title="Generate"
         onPress={() => generateRandomNumber()}
         color="#32a852"
        />
        <Text>{num}</Text>
        </View>
    )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can variables from state be imported into a TypeScript file?

Utilizing vue.js along with vuetify, I have a boolean value stored in state via Vuex defined in src/store/index.ts (named darkMode). This value is used within one of my view components inside a .vue file. However, I now wish to access the same variable in ...

Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function. calculeSalaire() { this.fraisGestion = this.getFraisGestion(); this.tauxFraisGestion = this.getTauxFraisGestion(); this.salaireBrut = this.getSalaireBrut(); this.salaireNet = this.g ...

How can I alter the icon's color?

Is it possible for the icon's color to change to red when the condition is greater than 0, and to gray when the condition is equal to zero? <TouchableOpacity onPress={() => { if (Object.values(selectedIt ...

A Guide to Implementing Schema.virtual in TypeScript

After switching from using schema.virtual in JavaScript to TypeScript, I encountered an error when trying to use it with TypeScript. Below is my code: UserSchema.virtual('fullname').get(function () { return `${this.firstName} ${this.lastName}` ...

Modify the code to use a BehaviorSubject subscribing to an Observable

Currently, I am in the process of learning Angular2 and RxJS by studying someone else's application. The application consists of two modules: asObservable.ts export function asObservable(subject: Subject) { return new Observable(fn => subject ...

The TypeScript error message states, "The property 'breadcrumb' is not found within the type 'Data'."

My Breadcrumb Component is functioning properly when compiled to JavaScript and displaying the desired output. However, my IDE is showing an error message that I am struggling to fix. The error states: [ts] Property 'breadcrumb' does not exist o ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Why is it considered an error when an index signature is missing in a type?

Consider the TypeScript code snippet below: type Primitive = undefined | null | boolean | number | string; // A POJO is simply meant to represent a basic object, without any complexities, where the content is unknown. interface POJO { [key: string]: ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

Furnish an item for a particular service

I am currently attempting to utilize a service created by another individual (github). This particular service requires a configuration to be passed to it. As stated in the repository: To configure Neo4jSettings in your bootstrap: provide('Neo4jSet ...

What is the best way to implement an onClick event listener in a TypeScript React application?

Is there a way to properly add an onClick event listener to a div element in my code snippet below? useEffect(() => { if (ref.current === null) { return; } const handleClick = (el: HTMLDivElement, e: MouseEvent) = ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

Using Typescript for AngularJS bindings with ng.IComponentController

Currently, I am utilizing webpack alongside Babel and Typescript Presently, the controller in question is as follows: // HelloWorldController.ts class HelloWorldController implements ng.IComponentController { constructor(private $scope: ng.IScope) { } ...

The error message "React Native - __DEV__ is not defined" has been

I am working on a project that involves [email protected]. I recently deleted the node_modules folder and then executed the following commands: npm i react-native upgrade However, I encountered the following error: react-native.js:15 ReferenceErr ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Utilizing Generics in TypeScript to Expand Abstract Classes

How can I define the property eventList in the class ImplTestClass to be an array with all possible values of AllowedEvents, while extending the class TextClass that accepts T? I'm stuck on this one. If anyone can provide guidance on how to achieve t ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

Problem updating data in AuthContext using React Native

In order to manage user information within the application, I have created a Context object called AuthContext. Once I retrieve the necessary user information using this Context object and perform the required operations, I save the data using AsyncStore a ...