How to properly type children in React Context
Asked Answered
B

1

7

In the project I'm creating a React Contex and I want to type properly the children, unfortunately in codesandbox only "any" type is accepted. Can You please look at it and suggest what type it should be ? I would like to avoid "any" type.

This is how Context.Provider is implemented

const App = () => {
  return (
    <BrowserRouter>
      <PostsContextProvider>
        <HeaderComponent />
        <ButtonsNavigation />
        <Routing />
      </PostsContextProvider>
      <DownBar />
    </BrowserRouter>
  );
};

export default App;

And here is the Context component

interface PostsContextValues {
  posts: PostType[];
}

export const PostsContext = createContext<PostsContextValues>({
  posts: []
});

export const PostsContextProvider = ({ children }: any) => {
  const value = useMemo(
    () => ({
      posts: data
    }),
    [data]
  );

  return (
    <PostsContext.Provider value={value}>{children}</PostsContext.Provider>
  );
};

thanks !

Borreri answered 23/12, 2022 at 22:50 Comment(1)
There is a PropsWithChildren helper you can use.Yabber
G
13

You can specify the type of the children prop in the PostsContextProvider component like this:

export const PostsContextProvider = ({ children }: { children: React.ReactNode }) => {
  const value = useMemo(
    () => ({
      posts: data
    }),
    [data]
  );

  return (
    <PostsContext.Provider value={value}>{children}</PostsContext.Provider>
  );
};

Here, the children prop is of type React.ReactNode, which represents a React node (e.g. an element, text, or fragment). This is a flexible type that allows any type of child to be passed to the PostsContextProvider component.

If you want to be more specific about the type of children that can be passed, you can create an interface or type that represents the shape of the children and use that instead of React.ReactNode. For example:

interface PostsContextProviderProps {
  children: JSX.Element | JSX.Element[]
}

export const PostsContextProvider = ({ children }: PostsContextProviderProps) => {
  // ...
};

This would allow only JSX elements or an array of JSX elements to be passed as children to the PostsContextProvider component.

Gunfire answered 23/12, 2022 at 22:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.