Skip to content

Commit 1eafe42

Browse files
authored
Update context.md
1 parent 4d3cf61 commit 1eafe42

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

docs/basic/getting-started/context.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,55 @@ id: context
33
title: Context
44
---
55

6+
## Basic Example
7+
8+
9+
```tsx
10+
import * as React from 'react';
11+
12+
interface AppContextInterface {
13+
name: string,
14+
author: string,
15+
url: string
16+
}
17+
18+
const AppCtx = React.createContext<AppContextInterface | null>(null);
19+
20+
// Provider in your app
21+
22+
const sampleAppContext: AppContextInterface = {
23+
name: 'Using React Context in a Typescript App',
24+
author: 'thehappybug',
25+
url: 'http://www.example.com'
26+
};
27+
28+
export const App = () => (
29+
<AppCtx.Provider value={sampleAppContext}>
30+
...
31+
</AppCtx.Provider>
32+
);
33+
34+
// Consume in your app
35+
36+
export const PostInfo = () => {
37+
const appContext = React.useContext(AppCtx)
38+
return (
39+
<div>
40+
Name: {appContext.name},
41+
Author: {appContext.author},
42+
Url: {appContext.url}
43+
</div>
44+
)
45+
}
46+
```
47+
48+
You can also use the [Class.contextType](https://reactjs.org/docs/context.html#classcontexttype) or [Context.Consumer](https://reactjs.org/docs/context.html#contextconsumer) API, let us know if you have trouble with that.
49+
50+
51+
*[Thanks to @AlvSovereign](https://github.com/typescript-cheatsheets/react/issues/97)*
52+
53+
## Extended Example
54+
655
Using `React.createContext` with an empty object as default value.
756

857
```tsx

0 commit comments

Comments
 (0)