I'm new to React, typescript and nextjs and I'm trying to pass multiple properties to a component. But, I seem to override them.
For example I have this in my _app.tsx
function App({ Component, myProps }: MyAppProps): JSX.Element {
const { ...props } = myProps;
return (
<MyStateProvider>
<Component {...props} />{' '}
</MyStateProvider>
);
}
In MyStateProvider, I have this in my-state-context.tsx
export const MyStateProvider: React.FC<any> = ( {children}) => {
const contextValue = doSomething();
return (
<MyStateContext.Provider value={contextValue}>
{children}
</MyStateContext.Provider>
);
};
However, I wish to something like this in my _app.tsx
function App({ Component, myProps }: MyAppProps): JSX.Element {
const { ...props } = myProps;
return (
<MyStateProvider {...props}>
<Component {...props} />{' '}
</MyStateProvider>
);
}
And this MyStateProvider in my-state-context.tsx
export const MyStateProvider: React.FC<any> = ( props, {children }) => {
const contextValue = doSomething(props); // <-- trying to accomplish passing props
return (
<MyStateContext.Provider value={contextValue}>
{children}
</MyStateContext.Provider>
);
};
What is the correct way to go about this?
CodePudding user response:
You can do the following:
function App({ Component, ...myProps }: MyAppProps): JSX.Element {
return (
<MyStateProvider {...myProps}>
<Component {...myProps} />
</MyStateProvider>
);
}
and in your provider, supposing that you are passing the component like this <MyStateProvider Children={SomeComponent}/>
// note that first letter of Children should be uppercase to behave as a component
export const MyStateProvider: React.FC<any> = ({Children, ...props}) => {
const contextValue = doSomething({...props});
return (
<MyStateContext.Provider value={contextValue}>
<Children />
</MyStateContext.Provider>
);
};
See the example