Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import './App.css';
  3. import PropTypes from 'prop-types';
  4.  
  5. const MyContext = React.createContext();
  6.  
  7. class MyProvider extends Component {
  8. state = {
  9. name: "Kishore",
  10. age: 25,
  11. cool: true
  12. }
  13. render() {
  14. return (
  15. <MyContext.Provider
  16. value={{
  17. state: this.state,
  18. growAYear: (val) => {
  19. this.setState({
  20. age: val
  21. });
  22. }
  23. }}
  24. >
  25. {this.props.children}
  26. </MyContext.Provider>
  27. );
  28. }
  29. }
  30.  
  31. const Family = (props) => {
  32. return (
  33. <div>
  34. <Person />
  35. </div>
  36. );
  37. };
  38.  
  39. class Person extends Component {
  40.  
  41. render() {
  42. return (
  43. <MyContext.Consumer>
  44. {(context) => (
  45. <React.Fragment>
  46. <pre>
  47. {JSON.stringify(context.state, undefined, 4)}
  48. </pre>
  49. <button
  50. type="button"
  51. onClick={() => context.growAYear(context.state.age + 1)}
  52. >Grow Age</button>
  53. </React.Fragment>
  54. )}
  55. </MyContext.Consumer>
  56. );
  57. }
  58.  
  59. }
  60.  
  61. class App extends Component {
  62.  
  63. constructor(props) {
  64. super(props);
  65. }
  66.  
  67. render() {
  68. return (
  69. <MyProvider>
  70. <div>
  71. <p>I'm the App</p>
  72. <Family />
  73. </div>
  74. </MyProvider>
  75. );
  76. }
  77.  
  78. }
  79.  
  80. export default App;
  81.  
  82. Person.propTypes = {
  83. name: PropTypes.any
  84. };
  85.  
  86. Family.propTypes = {
  87. name: PropTypes.any
  88. };
  89.  
  90. MyProvider.propTypes = {
  91. children: PropTypes.any
  92. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement