Giter Site home page Giter Site logo

taboca / doc-js-react-component-context-children-communication Goto Github PK

View Code? Open in Web Editor NEW
0.0 3.0 0.0 810 KB

Technote / ReactJS communication / Example of a child React component accessing a shared context and also executing a method

HTML 18.10% CSS 5.01% JavaScript 76.89%

doc-js-react-component-context-children-communication's Introduction

Study notes - React using the Context API

This is a simple application created with "create-react-app". It was initiated with the following execution:

npx create-react-app my-context-app

The initial checked code includes the following files:

  • ./app/SharedStore.js
  • ./app/FirstLevelElement.js
  • ./app/SecondLevelElement.js

The idea is to allow a child element to access a main store, and also to call a method so that to have the store data manipulated. For this, the example will use the new Context API from React.

Code changes to have the shared context at the child:

First we have created a SharedStore component that is responsible for the creation of a context named "SharedStoreContext" (using React.createContext()) and applying it to its children:

import React, { Component } from 'react';
export const SharedStoreContext = React.createContext();

export default class SharedStore extends Component {
  constructor(props) {
    super(props);
    this.state = { data: 'hello world'};
    this.execMethod = this.execMethod.bind(this);
  }
  execMethod() {
    this.setState({data: 'hi world 2'});
  }
  render() {
    return(
      <SharedStoreContext.Provider value = {{...this.state, execMethod: this.execMethod}}>
        {this.props.children}
      </SharedStoreContext.Provider>
    );
  }
}

Via doing that, it's possible to go back to the main App.js and simply wrap any component with the SharedStore:

import React, { Component } from 'react';
import SharedStore from './app/SharedStore';
import FirstLevelElement from './app/FirstLevelElement';

class App extends Component {
  render() {
    return (
      <div className="App">
        <SharedStore>
          <FirstLevelElement />
        </SharedStore>
      </div>
    );
  }
}

export default App;

The above should pass the elements of this.state (from SharedStore) plus one method, into FirstLevelElement's props — check above the value attribute associated with the SharedStoreContext.Provider

value = {{...this.state, execMethod: this.execMethod}}

Therefore FirstLevelElement is a component that should be able to access "data" and "sharedMethod" from it's render scope. FirstLevelElement will be then responsible for forwarding these to its child, SecondLevelElement:

import React, { Component } from 'react';
import {SharedStoreContext} from './SharedStore.js';
import SecondLevelElement from './SecondLevelElement.js';

export default class FirstLevelElement extends Component {
  render() {
    return(
      <SharedStoreContext.Consumer>
        { (sharedValue)  => {
          return(
            <SecondLevelElement data={sharedValue.data} sharedMethod={sharedValue.sharedMethod} />
          )
        }}
      </SharedStoreContext.Consumer>
    );
  }
}

And finally,

import React, { Component } from 'react';

export default class SecondLevelElement extends Component {
  componentWillMount() {
    this.props.sharedMethod();
  }
  render() {
    return(
      <div>{this.props.data}</div>
    );
  }
}

doc-js-react-component-context-children-communication's People

Contributors

taboca avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.