Unable to remove useRef value when it’s set react ionic

Issue

The problem I’m currently facing is that I’m able to change the value of the useRef<HtmlIonInputElement> but when I go to the input I’m unable to remove the text.

I tried changing const nameInput to let nameInput but that didn’t work. Could someone tell me how I can set a value that’s also removable with backspace? Thank you.

import { IonPage, IonLabel, IonContent, IonInput, IonText, IonItem, IonList } from '@ionic/react';
import { useEffect, useRef } from 'react';

export const TestPage2: React.FC  () > {
    const nameInput  useRef<HTMLIonInputElement>(null);
    useEffect(() > {
        if (nameInput.current) {
            nameInput.current.innerText  "Kirito";
        }
    }, []);
    return (
        <IonPage>
            <IonContent fullscreen>
                <IonList lines"full" class"ion-no-margin ion-no-padding">
                    <IonItem>
                        <IonLabel position"stacked">
                            the name input
                        </IonLabel>
                        <IonInput required type"text" ref{nameInput}></IonInput>
                    </IonItem>
                </IonList>
            </IonContent>
        </IonPage>
    );
}

enter image description here

Solution

As you are using React it is preferable to use the UseState hook to manipulate your variables. From what I understand you are trying to edit the IonInput tag; in which case you don’t need useRef.

export const TestPage2: React.FC  () > {
const [nameInput, setNameInput]  useState("Kirito, best swordman");
return (
    <IonPage>
        <IonContent fullscreen>
            <IonList lines"full" class"ion-no-margin ion-no-padding">
                <IonItem>
                    <IonLabel position"stacked">
                        the name input
                    </IonLabel>
                    <IonInput required type"text" onIonChange{(e: any) > setNameInput(e.detail.value)} value{nameInput}></IonInput>
                </IonItem>
            </IonList>
        </IonContent>
    </IonPage>
  );
}

Answered By – Yannick Lionel

Leave a Comment