Home > Back-end >  How to type a React.createContext for typescript, which takes a ref and a setState function?
How to type a React.createContext for typescript, which takes a ref and a setState function?

Time:11-10

I am getting this error (amongst others):

Type 'Dispatch<SetStateAction<null>>' is not assignable to type '() => void'

I have basically this:

import React, {
  ReactElement,
  ReactNode,
  useEffect,
  useRef,
  useState,
  useContext,
} from 'react';

export const ScrollToContext = React.createContext({
  ref: React.createRef(),
  setScrollTo: () => {},
});

export function useScrollTo() {
  return useContext(ScrollToContext);
}

I want the value of the context provider to have 2 properties: a ref, and a setScrollTo which is a setState function. How do I type those in TypeScript?

How do I properly initialize React.createContext, and how do I type the useScrollTo() return value?

export function useScrollTo(): ??? {
  return useContext(ScrollToContext);
}

CodePudding user response:

You can use an interface to specify the types of the context. Try this:

interface IScrollToContext {
  ref: RefObject<undefined>;
  setScrollTo: Dispatch<SetStateAction<string>>; // I am assuming the state type is a string
}

// Now you can initialize it without errors
export const ScrollToContext = createContext<IScrollToContext>({
  ref: createRef(),
  setScrollTo: () => {},
});

You don't need to specify the return type of the useScrollTo function hook. Typescript infers the type for you. But if you want to do it explicitly, do this:

export function useScrollTo(): IScrollToContext  {
  return useContext(ScrollToContext);
}
  • Related