Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot useRef() in functional component. null is not an object

I have a functional component which causes the following error:

null is not an object (evaluating ‘textInput.current.blur’

I wonder why

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, { useState, useRef } from "react";
import { TextInput } from "react-native";

const UselessTextInput = ({ hide }) => {
    const [text, onChangeText] = React.useState("Useless Text");
    const textInput = useRef(null);

    const _renderInput = () => {
        if (hide) textInput.current.blur();
        <TextInput
            ref={textInput}
            onFocus={() => ...}
            onChangeText={onChangeText}
            value={text} />

    ...

    return __renderInput();
}

Can anyone explain this behaviour?

>Solution :

use optional chaining to your textInput value

like this : textInput?.current?.blur();

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading