最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Context Provider error with typescript - Stack Overflow

programmeradmin2浏览0评论

I'm trying to create an auth/session context for my application. However, I am facing some errors when I attempt to build the Provider ponent and pass the children as props.


const AuthContext = createContext({})

type Props = {
    children: ReactNode
}

export const AuthProvider = ({children}: Props) => {
    return(
        <AuthContext.Provider>{children}</AuthContext>
    )
}

The following errors are appearing:

Cannot find namespace 'AuthContext'.ts(2503)

Unterminated regular expression literal.ts(1161)

I tried to write the code with more information to see if it was a type error, but it didn't solve the problem. When I try to take the same code and change the extension from TSX to JS the errors disappear.

I'm trying to create an auth/session context for my application. However, I am facing some errors when I attempt to build the Provider ponent and pass the children as props.


const AuthContext = createContext({})

type Props = {
    children: ReactNode
}

export const AuthProvider = ({children}: Props) => {
    return(
        <AuthContext.Provider>{children}</AuthContext>
    )
}

The following errors are appearing:

Cannot find namespace 'AuthContext'.ts(2503)

Unterminated regular expression literal.ts(1161)

I tried to write the code with more information to see if it was a type error, but it didn't solve the problem. When I try to take the same code and change the extension from TSX to JS the errors disappear.

Share Improve this question asked Jul 11, 2023 at 11:45 Bruno BispoBruno Bispo 3033 silver badges14 bronze badges 2
  • 1 The unterminated expression error occured because you closed your tag with AuthContext and not AuthContext.Provider. For the main problem, can you provide a working sandbox containing the error ? – Florent M. Commented Jul 11, 2023 at 11:52
  • I just copied and pasted your code in my VScode and it works, it just points out that you need to close <Authcontext.Provider> with </AuthContent.provider> and that it need value as a parameter – Gabriel Nadaleti Commented Jul 11, 2023 at 11:53
Add a ment  | 

2 Answers 2

Reset to default 8

For the first issue that you are facing:- Cannot find namespace 'AuthContext'.ts

Change your .ts file to .tsx And in your tsconfig.json file make sure that jsx option is set to react-jsx under piler options as below:-

"pilerOptions": {
    "jsx": "react-jsx"
...
}

For your second issue:- unterminated expression

Just close your <AuthContext.Provider> with </AuthContext.Provider>as below:-

const AuthContext = createContext({})

type Props = {
    children: ReactNode
}

export const AuthProvider = ({children}: Props) => {
    return(
        <AuthContext.Provider>{children}</AuthContext.Provider>
    )
}

Change your file extension from .ts to .tsx

发布评论

评论列表(0)

  1. 暂无评论