Home > Mobile >  useContext Provider in TypeScript
useContext Provider in TypeScript

Time:04-14

I'm developing a project where I have a Context, and I got this error when trying to use the Provider:

Type '{ children: Element[]; }' is not assignable to type 'IntrinsicAttributes & ReactNode'.
  Type '{ children: Element[]; }' is missing the following properties from type 'ReactPortal': key, type, props

Mainpage.tsx

import { Form } from "../../components/Form";
import { Greet } from "../../components/Greet";

import { UserProvider } from "../../context/UserContext";

const Mainpage: React.FC = () => {

    return(
        <div>
            <UserProvider> // **ERROR HERE !!!**
                <Greet />
                <Form />
            </UserProvider>
        </div>
    )
}
export default Mainpage;

UserContext.tsx

import React, { Component, createContext, ReactChild, ReactNode, useState } from "react";

type ContextType={
    name?:string,
    email?:string,
    submit?: (param?:any, param2?:any)=> void
}

export const UserContext = createContext<ContextType | null> (null);

export const UserProvider: React.FC<React.ReactNode> = (children) => {
    const [name, setName] = useState('')
    const [email, setEmail] = useState('')

    const onSubmit = (name:string, email:string ) => {

        console.log('Submit App: '   name, email)
        setName(name)
        setEmail(email)
    }

    return(
        <UserContext.Provider value={{name, email, submit: onSubmit}}>
            {children}
        </UserContext.Provider>

    )
}

CodePudding user response:

UserProvider is defined as a React component and accept just one children UserProvider: React.FC<React.ReactNode>

You can wrap <Greet /> and <Form/> inside a fragment

<>
  <Greet/>
  <Form/>
</>
....
const Mainpage: React.FC = () => {

    return(
        <div>
            <UserProvider> // **ERROR HERE !!!**
              <>
                <Greet/>
                <Form/>
              </>
            </UserProvider>
        </div>
    )
}
export default Mainpage;

CodePudding user response:

By explicitly setting React.ReactNode as your component props you are saying that there will only be one node as a child and currently you've got 2 nodes as children.

Change this:

export const UserProvider: React.FC<React.ReactNode>

To this:

export const UserProvider: React.FC

An alternative option is to wrap the children in a React Fragment like this:

<UserProvider> // **ERROR HERE !!!**
  <>
    <Greet />
    <Form />
  </>
</UserProvider>
  • Related