2

I'm trying to re-write my app using React Context API but have faced with the next issue - the value I'd like to pass through Provider to Consumer is not passed.

Initial State:

let initialState = {
    ve: 'randomValue'
};

export default initialState;

Provider:

import React, {Component} from 'react';
import MyContext from './myContext';

import initialState from './initialState';

class MyProvider extends Component{
constructor(props) {
    super(props);
    this.state = initialState;
}

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

export default MyProvider;

Consumer:

import React, {Component} from 'react';
import {Text, View} from 'react-native';

import MyContext from './Context/myContext';

export default class App extends Component {
  render() {
    return (
      <MyContext.Consumer>
        {context => (
          <View>
            <Text>
              {context}
            </Text>
          </View>
        )}
      </MyContext.Consumer>
    );
  }
}

I don't get any errors but no Context value as well.

1
  • Is App component rendered as a child of MyProvider? Commented Feb 24, 2019 at 19:22

1 Answer 1

0

You need to use the Provider component somewhere above the MyContext.Consumer component as well.

Example

const initialState = {
  ve: "randomValue"
};
const MyContext = React.createContext();

class MyProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = initialState;
  }

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

class App extends React.Component {
  render() {
    return (
      <MyProvider>
        <MyContext.Consumer>
          {context => <div>{JSON.stringify(context)}</div>}
        </MyContext.Consumer>
      </MyProvider>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.