Creating a bespoke numeric input component using React Native

As I work on developing a numericInput component, my goal is to streamline the code by eliminating RNTextInput. The part that confuses me is how it utilizes

React.forwardRef<RNTextInput, Props>((props, ref) => {
    const { onChangeText, ...rest } = props;

What is the purpose of passing ref?

import React, { useCallback } from "react";
import { TextInput as RNTextInput, StyleSheet, TextInputProps, View } from "react-native";
import { BaseTextInput } from "src/components/atoms/BaseTextInput";
import { colorsConst } from "src/styles/const/colorsConst";

type Props = Omit<TextInputProps, "keyboardType" | "selectionColor" | "autoCapitalize"> & {
  disabled?: boolean;
};

export const NumericInput = React.memo(
  React.forwardRef<RNTextInput, Props>((props, ref) => {
    const { onChangeText, ...rest } = props;

    const onChanged = useCallback(
      (text: string) => {
        return onChangeText ? onChangeText(text.replace(/[^0-9]/g, "")) : undefined;
      },
      [onChangeText],
    );

    return (
      <View style={styles.container}>
        <BaseTextInput
          ref={ref}
          style={[
            styles.text,
            {
              ...(rest.disabled ? { color: colorsConst.DISABLED } : {}),
            },
          ]}
          {...rest}
          keyboardType="number-pad"
          onChangeText={onChanged}
        />
      </View>
    );
  }),
);

NumericInput.displayName = "NumericInput";

const styles = StyleSheet.create({
  container: {
    borderRadius: 5,
    borderWidth: 1,
    borderColor: colorsConst.DIVIDER,
  },
  text: {
    width: "100%",
    fontSize: 14,
    paddingHorizontal: 18,
  },
});

Answer №1

In order to assign the ref at the level of the consuming component, you need to pass it accordingly. Refs are specifically passed outside of normal props as they act as references to DOM nodes. More information on this can be found in the documentation for forwardRef.

By doing so, you enable yourself to call functions like inputRef.current.focus() on a personalized text input field. The process involves creating the ref within the custom component and passing it along to the TextInput component. Here is a pseudocode example:

const MyCustomInput = React.forwardRef((props, ref) => {
  return <TextInput ref={ref} {...props} />;
});

const App = () => {
  const inputRef = useRef(null);
  
  useEffect(() => {
    inputRef.current?.focus():
  }, [inputRef]);

  return <MyCustomInput ref={inputRef} />;
};

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

React Native React Thunk activating upon the initial rendering of a component and every time a key is pressed in an input field

As a newcomer to react, react-native, react-redux, and react-thunk, I find myself facing a strange issue that is puzzling me. The sign-in component I have implemented uses a thunk for user authentication. I have mapDispatchToProps and applied it to the co ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Using custom Components to accept HTML input

I have recently developed a custom component to arrange content within IonCardContent. It has been effective for my current requirements: interface ContainerProps { position?: string; content?: string, colour?: string; custClass?: string; } ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

Troubleshooting problem with refreshing URL on "ionic serve" mode

After transitioning my project from Ionic 2 to Ionic 3, I've encountered an issue with ionic serve and the rebuilding process. Initially, when I build the project, everything functions as expected. However, I've noticed that the URL in the brows ...

Fetching data from React Router v6 Navigate

When I navigate to a new route, I am encountering an issue with passing state data in TypeScript. The error message says: Property 'email' does not exist on type 'State'." The parent functional component looks like this: naviga ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

Angular: How can the dropdown arrow in 'ng-select' be eliminated?

Is there a way to hide the dropdown arrow in an 'ng-select' element in Angular? <div class="col-md-6"> <ng-select id="selectServiceType" [items]="clientServiceTypes$ | async" pl ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Error: React-Redux Provider is being called incorrectly

I am currently working on a small application to get familiar with using Redux Toolkit. My understanding of React/Redux mainly comes from an outdated Udacity course. Although the error message lists the top 3 reasons for this particular error, none of the ...

Issue with expanding TileLayer using TypeScript 2.0 and Angular 2: Unable to implement Leaflet Leaflet

Trying to incorporate the Microsoft Map API into my app has been a challenge, especially when I encounter errors like the one below when calling L.tileLayer.extend: Here is the snippet of my code: import { Component, OnInit } from '@angular/core&apo ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...

Cease the animated loading icon once the template has finished loading in sync with the async pipe

.ts initialize() { const loadingScreen = await this.loadingService.displayLoader();//loading screen this.products$ = this.bikeShopService.retrieveData();//Observable operation } .html <ion-col size="6" *ngFor="let product of (products$ ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...