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 ?
>Solution :
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>
)
}