Sunday, 17 March 2019

Sample React Context: Provider/Consumer

index.js 

import React from "react";
import ReactDOM from "react-dom";
import Provider, {Context} from '../context'

function App() {
   return (
      <Provider>
         <div className="App">
         <h1>This is the heading</h1>
         <Context.Consumer>
             {ctx => ctx.number}
         </Context.Consumer>
         <Context.Consumer>
               {ctx => <button onClick={ctx.inc}>inc</button>}
         </Context.Consumer>
         </div>
      </Provider>
   );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


context.js (or store.js)

import React from "react";
import ReactDOM from "react-dom";

export const Context = React.createContext();

class Provider extends React.Component {
   state = {
      number: 0,
      inc: () => this.setState({ number: this.state.number + 1 })
   };

   render() {
      return (
          <Context.Provider value={this.state}>
              {this.props.children}
          </Context.Provider>
      );
   }
}

export default Provider;

No comments:

SQL: Generate a range of numbers

SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n FROM       (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),      (VALU...