mfsiat
11/13/2019 - 6:50 AM

Context API

// 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