Skip to content

Instantly share code, notes, and snippets.

@dmcshehan
Created May 19, 2020 05:34
Show Gist options
  • Save dmcshehan/b78aa677234e422060aada606f05b9fd to your computer and use it in GitHub Desktop.
Save dmcshehan/b78aa677234e422060aada606f05b9fd to your computer and use it in GitHub Desktop.
How to use React Context

Context

Better to create the Context instance in a seperate file.

//MyContext.js

import {React} from 'react';

const MyContext = React.createContext({});
export const MyContextProvider = MyContext.Provider;

export default MyContext;

Passing a context value with Provider

//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


import { MyContextProvider } from './MyContext';

ReactDOM.render(
  <MyContextProvider value={{ name: 'Shehan' }}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </MyContextProvider>,
  document.getElementById('root')
);

Referencing Context in a functional component

//App.js

import React from 'react';
import NameContext from './NameContext';


function App(props) {
  return (
    <NameContext.Consumer>
      {({ name }) => (
        <div className="App">
          <p>{name}</p> 
        </div>
      )}
    </NameContext.Consumer>
  );
}

export default App;

Referencing Context in a Class component

import React, { Component } from 'react';
import MyContext from './MyContext';

export default class reactAuth0Spa extends Component {
  render() {
    return <p>Context Name : {this.context.name}</p>;
  }
}

reactAuth0Spa.contextType = MyContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment