Guest User

Untitled

a guest
Mar 24th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. import React, { Component } from 'react';
  2.  
  3. // Create a context first of all //
  4. const MyContext = React.createContext();
  5.  
  6. // Make a component class which returns the context using a provider //
  7. class MyContextProvider extends Component {
  8. constructor(props) {
  9. super(props);
  10.  
  11. this.state = {
  12. name: "Aakash",
  13. like: "Write Code",
  14. count:1
  15. };
  16. }
  17.  
  18. changeCount = () =>{
  19. this.setState({count:this.state.count+1})
  20. }
  21. //using this.props.children because we want it to be accessible to every child //
  22. render() {
  23. return (
  24. <div>
  25. <MyContext.Provider value={[this.state.name,this.state.like,this.state.count,this.changeCount]}>
  26. {this.props.children}
  27. </MyContext.Provider>
  28. </div>
  29. )
  30. }
  31. }
  32. // access context in a component using context.consumer.
  33. // NOTE: It works using render props
  34. class Component2 extends Component {
  35.  
  36. render() {
  37. return (
  38. <div>
  39.  
  40. <MyContext.Consumer>
  41. {
  42. (context) => (
  43. <React.Fragment>
  44. <p>My Name is:{context[0]}</p>
  45. <p>I Like To:{context[1]}</p>
  46. <p>Count:{context[2]}</p>
  47. <button onClick={context[3]}>Click To Increase Count</button>
  48. </React.Fragment>
  49. )
  50. }
  51. </MyContext.Consumer>
  52. </div>
  53. )
  54. }
  55. }
  56.  
  57. class Component1 extends Component {
  58.  
  59. render() {
  60. return (
  61. <div>
  62. <Component2 />
  63. </div>
  64. )
  65. }
  66. }
  67.  
  68. class App extends Component {
  69.  
  70. render() {
  71. return (
  72. // Enclose all your components which need access to context inside the provider //
  73. <MyContextProvider>
  74. <div>
  75. <Component1 />
  76. </div>
  77. </MyContextProvider>
  78. );
  79. }
  80. }
  81.  
  82. export default App;
Add Comment
Please, Sign In to add comment