O
O
Ostic2019-06-04 16:01:12
typescript
Ostic, 2019-06-04 16:01:12

How to use context with useContext hook?

Hello.
App.tsx

const Hello = createContext<string>('Hello');

function App() {
  return (
    <Hello.Provider value='Hi'>
        <MyComponent />
    </Theme.Provider>
  );
}
export default App;

MyComponent.tsx
const MyComponent: React.FC<> = () => {
  const msg = useContext<string>(Hello);
  return (
    <span>{msg}</span>
   )
}

Writes in the component:
Cannot find name 'Hello'.ts(2304)

Everything is simplified to the maximum.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dev null, 2019-06-04
@Ostic

rewrote the answer
here doc

const Hello = createContext<string>('Hello');
export default Hello;

import Hello from 'HelloContext';
import MyComponent from 'MyComponent';

function App() {
  return (
    <Hello.Provider value='Hi'>
        <MyComponent />
    </Hello.Provider>
  );
}
export default App;

import HelloContext from 'HelloContext';

const MyComponent: React.FC<> = () => {
  const msg = useContext(HelloContext );
  return (
    <span>{msg}</span>
   )
}

export default MyComponent;

PS
</Theme.Provider> <-- откуда Theme?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question