Home > Software engineering >  Unable to remove useRef<HTMLIonInputElement> value when it's set react ionic
Unable to remove useRef<HTMLIonInputElement> value when it's set react ionic

Time:09-22

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

CodePudding user response:

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>
  );
}
  • Related