skip to Main Content

I’m using react and nextjs, here is my following code which throws an error on children props as property children does not exist on type {}

import { NextPage } from "next";
import { createContext, useContext, useReducer, Dispatch } from "react";

import { GlobalStatesType } from "../types";
import reducer, { ActionType, initialState } from "../reducers";

export const StateContext = createContext<{
  states: GlobalStatesType;
  dispatch: Dispatch<ActionType>;
}>({
  states: initialState,
  dispatch: () => {},
});


export const StateProvider: NextPage = ({ children }) => {
  const [states, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={{ states, dispatch }}>
      { children }
    </StateContext.Provider>
  );
};

export const useStatesValue = () => useContext(StateContext);

how to write in the context of the next function that I imported?

2

Answers


  1. It looks like you’re using TypeScript and Next.js to create a context provider component. The error you’re encountering, "Property ‘children’ does not exist on type ‘{}’", is likely due to TypeScript not recognizing the children prop in the function component.

    To resolve this issue, you can explicitly define the type of the children prop in the StateProvider component. Here’s how you can do it:

    import { NextPage } from "next";
    import { createContext, useContext, useReducer, Dispatch, ReactNode } from "react"; // Import ReactNode type
    
    import { GlobalStatesType } from "../types";
    import reducer, { ActionType, initialState } from "../reducers";
    
    type StateProviderProps = {
      children: ReactNode; // Define the type of the children prop
    };
    
    export const StateContext = createContext<{
      states: GlobalStatesType;
      dispatch: Dispatch<ActionType>;
    }>({
      states: initialState,
      dispatch: () => {},
    });
    
    export const StateProvider: NextPage<StateProviderProps> = ({ children }) => { // Use StateProviderProps type
      const [states, dispatch] = useReducer(reducer, initialState);
    
      return (
        <StateContext.Provider value={{ states, dispatch }}>
          {children} {/* Use children directly */}
        </StateContext.Provider>
      );
    };
    
    export const useStatesValue = () => useContext(StateContext);
    

    By defining the StateProviderProps type and using it to specify the type of the children prop in the StateProvider component, you should no longer encounter the TypeScript error related to the children prop.

    Login or Signup to reply.
  2. You can solve it like this:

    export const StateProvider: NextPage = ({ children }: {
      children: React.ReactNode;
    }) {}
    

    Because you’re not defining the props type, it became type {} and property children is indeed not exist on type {}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search