1

I am trying to make a context with hooks in react with typescript like this:

// StateGlobalContext.ts
import React, { Dispatch, ReactNode, SetStateAction } from "react";

export interface StateGlobalContextType {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = React.createContext<StateGlobalContextType>({} as StateGlobalContextType);

export default function StateGlobalProvider({ children: ReactNode }): React.FC<ReactNode> {
  const [loading, setLoading] = React.useState<boolean>(false);

  return (
    <StateGlobalContext.Provider value={{ loading, setLoading }}>
      {props.children}
    </StateGlobalContext.Provider>
  )
}

But for some reason i don't know why, return get problem like this

Type '{}' is missing the following properties from type 'ReactElement<any, any>': type, props, key

and i cannot declare StateGlobalContext.Provider, the error message like this

Cannot find namespace 'StateGlobalContext'

1 Answer 1

1

This is an error to do with how you're handling your props input.

When destructuring in Typescript doing { children: ReactNode } destructures the children attribute from props, assigning it to a variable called ReactNode. Then, rather than calling ReactNode (which would still be an error because you've imported it too), you're using props.children, which is not defined.

Instead use the syntax: { children }: { children: ReactNode }, although this is easier if you use an interface.

import React, { Dispatch, ReactNode, SetStateAction, createContext } from "react"

export interface StateGlobalContextType {
    loading: boolean
    setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = createContext<StateGlobalContextType>({} as StateGlobalContextType)

interface StateGlobalProviderProps {
    children: ReactNode
}
const StateGlobalProvider: React.FC<StateGlobalProviderProps> = ({ children }: StateGlobalProviderProps) => {
    const [loading, setLoading] = React.useState<boolean>(false)

    return <StateGlobalContext.Provider value={{ loading, setLoading }}>{children}</StateGlobalContext.Provider>
}

export default StateGlobalProvider

Also, rather than declaring the return type of function as React.FC<ReactNode>, declare the component itself as type React.FC<StateGlobalProviderProps>

Sign up to request clarification or add additional context in comments.

2 Comments

That solves the return problem, StateGlobalContext.Provider problem is not over yet, but thank you @Ben Rauzi
The context problem has been solved, i follow this article bobbyhadz[dot]com/blog/react-cannot-find-namespace-context

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.