Reputation: 1171
I have a super simple app like
import React, { createContext } from 'react';
import { render } from 'react-dom';
import './style.css';
interface IAppContext {
name: string;
age: number;
country: string;
}
const AppContext = createContext<IAppContext | null>(null);
const App = () => {
const contentValue: IAppContext = {
name: 'Paul',
age: 21,
country: 'UK',
};
return (
<AppContext.Provider value={contentValue}>
<div>{name}</div>
</AppContext.Provider>
);
};
render(<App />, document.getElementById('root'));
I'm just trying to use the context but in <div>{name}</div>
I get the error
'name' is deprecated.(6385)
lib.dom.d.ts(19534, 5): The declaration was marked as deprecated here.
Type 'void' is not assignable to type 'ReactNode'.(2322)
index.d.ts(1183, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
const name: void
@deprecated
Is this the correct way to use context?
Is it the way I'm using typescript that is casuing this error ?
Upvotes: 0
Views: 493
Reputation: 157
Context is basically a very simple state management tool. In simple words, if you had a parent component with some state initialized, what you would have to do to access this state in child components is pass it down as props. If you have 10 child components you would have to do that manually 10 times which isn't very practical. So useContext basically warps the parent component and the every child component can access that context. In your case:
interface IAppContext {
name: string;
age: number;
country: string;
}
const AppContext = createContext<IAppContext | null>(null);
const App = () => {
const contentValue: IAppContext = {
name: 'Paul',
age: 21,
country: 'UK',
};
return (
<AppContext.Provider value={contentValue}>
<ChildComponent/> // now let's say you another child component here.
</AppContext.Provider>
);
};
const ChildComponent = () => {
const appContext = useContext(AppContext);
return <div>appContext.name</div>
}
export default Home
As you can see you can access the context in child components as well.
Upvotes: 0
Reputation: 897
usually you would use useContext. But in your current example, you can use the object value directly by changing name
to contentValue.name
.
To further explain;
Context Providers allow you to access a context provider's value using a hook called useContext
. When you call this hook you pass in the Context that you wish to target. In this case it would be useContext(AppContext)
. This gives you access to the value
prop of the <AppContext.Provider />
, in your case, this value is equal to contentValue
.
Example;
const MyComponent = () => {
const appContext = useContext(AppContext);
return (
<div>
{appContext.name}
</div>
)
}
Upvotes: 1