Reputation:
export function TodosContextProvider( {children}: {children: React.ReactNode}, props: any) {
const [todos, dispatch] = React.useReducer(todosReducer, [
{
Id: 1,
Title: 'Learn Context API',
Done: true
},
{
Id: 2,
Title: 'Learn TypeScript',
Done: true
},
{
Id: 3,
Title: 'Use Context API with TypeScript',
Done: false
}
]);
console.log(props.siteUrl);
return (
<TodosDispatchContext.Provider value={dispatch}>
<TodosStateContext.Provider value={todos}>
{children}
</TodosStateContext.Provider>
</TodosDispatchContext.Provider>
);
}
I have this TodosContextProvider, I wrote it and then added an additional argument called props in the hope that I could pass some additional arguments to my function component from the root class.
export default class Crud extends React.Component<ICrudProps, {}> {
public render(): React.ReactElement<ICrudProps> {
return (
<TodosContextProvider props={this.props}>
<TodoForm />
<TodoList />
</TodosContextProvider>
);
}
}
I did the following and passed this.props to props in order to log it and see the content from TodosContextProvider, but this throws me an error.
Type '{ children: Element[]; props: Readonly<ICrudProps> & Readonly<{ children?: ReactNode; }>; }' is not assignable to type 'IntrinsicAttributes & { children: ReactNode; }'.
Property 'props' does not exist on type 'IntrinsicAttributes & { children: ReactNode; }'.ts(2322)
It seems I can't just add an argument the conventional way if I use children as an argument. How do I do what I intend to do?
Upvotes: 0
Views: 3364
Reputation: 16309
The first argument to a component are the props. children
is always just one property of that object. React automatically adds it to the props with whatever you put between the opening and closing tag of your component. If you want to access all the other properties as props
you can use the spread operator. Change your function signature to:
export function TodosContextProvider( {children, ...props}: {children: React.ReactNode, [x: string]: any}) { /* ... */}
This extracts the property children
from the props and gives you any additional props as an object props
.
Then you can use it like:
<TodosContextProvider foo="bar" {...this.props}>
{/* ... */}
</TodosContextProvider>
Upvotes: 3
Reputation: 2799
well, you can have to define a prop type
type TodoCotextProviderProps {
children: React.ReactNode,
// any aditional props you might have
}
and in the signutire of your component
export function TodosContextProvider(props: TodoCotextProviderProps )
Upvotes: 0