Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Typescript, how to use Context?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  )
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading