A step-by-step guide to resolving the 'Type is not assignable error' in Typescript when dealing with an array of elements

Struggling to make this work, facing the same error repeatedly. Since I am still new to Typescript, a breakdown of what this error message signifies would be greatly appreciated:

const itemsRef = useRef<Array<HTMLLIElement | null>>([]);

...

<li
  ref={(el) => (itemsRef.current[index] = el)}
/li>

The error message reads as follows:

Type '(el: HTMLLIElement | null) => HTMLLIElement | null' is not assignable to type 'LegacyRef<HTMLLIElement> | undefined'.
  Type '(el: HTMLLIElement | null) => HTMLLIElement | null' is not assignable to type '(instance: HTMLLIElement | null) => void | (() => VoidOrUndefinedOnly)'.
    Type 'HTMLLIElement | null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.
      Type 'null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.

Answer №1

The error message you are encountering indicates that the function assigned to the `ref` prop does not match React's expected type. The `ref` should be a function returning `void` or a `RefObject`, but in this case, it returns `HTMLLIElement | null`, which is incompatible.

To resolve this issue, consider using a callback ref instead of directly assigning to the array.

import React, { useRef, useEffect } from 'react';

function YourComponent() {
 const itemsRef = useRef<Array<HTMLLIElement | null>>([]);

 useEffect(() => {
    // Initialize itemsRef.current if empty
    if (!itemsRef.current) {
      itemsRef.current = [];
    }
 }, []);

 const setRef = (el: HTMLLIElement | null, index: number) => {
    if (!itemsRef.current) {
      itemsRef.current = [];
    }
    itemsRef.current[index] = el;
 };

 return (
    <ul>
      {/* Example usage */}
      {Array.from({ length: 5 }).map((_, index) => (
        <li key={index} ref={(el) => setRef(el, index)}>
          Item {index + 1}
        </li>
      ))}
    </ul>
 );
}

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

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Bringing PNGs and SVGs into React - Error TS2307: Module not found

While attempting to import PNGs/SVGs (or any other image format) into my React project, TypeScript presents the following error: TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations. The frontend ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Connect values with formBuilder in Angular

I have an array of objects structured like this const premises = [ { question: '1', value: '1' }, { question: '2', value: '2' }, { question: '3', value: '3' } ] ...

Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask: public send_login(user){ console.log(user) return this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions) .pip ...

What causes the object type to shift away from 'subscribe'?

Currently, I am facing an issue with retrieving a Coupon object from the server using a REST API in combination with Angular. The problem arises when I attempt to access the 'subscribe' method - within the 'subscribe', the object is of ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Retrieve the vertical distance of an element's top edge from the browser window

I'm currently working on a hook that calculates the offsetTop of an element. This is crucial for applying styles to make the header stick to the top. import { useState, useEffect } from 'react'; interface ElementPosition { left: number ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Appending or removing a row in the P-Table will result in updates to the JSON

My task involves implementing CRUD (Create, Read, Update, Delete) functionality for my table. While Create, Read, and Update are working fine with the JSON file, I am struggling to figure out how to delete a specific row in the table without using JQuery o ...

Exploring Angular 5's BehaviourSubject for validating multiple email fields

Working with Angular5, I have a project page that includes an upload feature using a core upload component from my organization. Users can upload up to 5 files and must fill in the email field before clicking the "upload" button. My goal is to trigger a s ...

Utilizing Async Storage for Language Localization

Currently, I am utilizing two separate APIs for localization, both of which return JSON data. getEnLoc() //400kb getEsLoc() //400kb My plan is to call these APIs in App.ts during the app's initialization phase and store the retrieved JSON objects in ...

How to retrieve an image from a Spring RestController using Angular and store it in the

Currently, I am working on a Client-Server application that utilizes SpringBoot and Angular2. One of the functionalities I have implemented successfully is loading an image from the server based on its filename. At the client-side, I store the attribute i ...

Having trouble integrating ColorThief with Angular, encountering issues with missing library methods?

I am attempting to integrate the Library ColorThief () into an Angular 12 project, but unfortunately, I have been unable to make it work. I started by running $ npm i --save colorthief and then in my desired component .ts file: const ColorThief = require ...

Encountering build issues in my next.js application post updating to version 12.#.# and implementing Typescript

In my next.js application, I recently upgraded to version 10 and added TypeScript to the mix. Despite ironing out all issues during development, I encountered errors when running yarn next build due to my use of the keyword interface. ./src/components/ ...

What is the best way to switch to a different screen in a React Native application?

I've recently dived into the world of React Native and embarked on a new project. The initial screen that greets users upon launching the app is the "welcome screen," complete with a prominent 'continue' button. Ideally, clicking this button ...

In relation to the characteristics of an Angular Component (written in TypeScript) Class

I am attempting to create a circle on a canvas using Angular. I have followed the necessary steps and have a basic understanding of how everything works. Although my IDE is not showing any errors, when I run the code, the console displays an error stating ...