Skip to content

Instantly share code, notes, and snippets.

@mfsiat
Created November 13, 2019 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfsiat/5028104d423ff87cfde14fbfeb527ca7 to your computer and use it in GitHub Desktop.
Save mfsiat/5028104d423ff87cfde14fbfeb527ca7 to your computer and use it in GitHub Desktop.
// Here lists the provider
// because of exporting consumers also we are not exporting it as default
// our track changes with its state so we are creating a provider
// here and we can wrap all our compoments inside this provider
// using only the consumer
import React, { Component } from 'react';
const Context = React.createContext();
export class Provider extends Component {
state = {
track_list: [
{ track: { track_name:'abc' } },
{ track: { track_name:'123' } },
],
heading: 'Top 10 Tracks' // the heading changes after the search
}
render() {
return (
<Context.Provider value={this.state} > // the value entered here can be fetch from any consumer
{this.props.children}
</Context.Provider>
)
}
}
// we need to export the consumer by creating constant variable Consumer
export const Consumer = Context.Consumer;
import React, { Component } from 'react'
import { Consumer } from '../../context'; // importing the consumer from the context.js
class Tracks extends Component {
render() {
return (
<Consumer>
{value => {
// the value will be passed from the context.js
}}
</Consumer>
)
}
}
export default Tracks;
// the value of the state from context provider will be passed inside this value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment