How do I use context to share state between a class and a functional component in react?

Viewed 1674

I have a top level context Provider, followed by a Parent class component follow by a functional stateless Child.

I can update the my context value from the Child, but not from the parent, even though the value updates in the parent.

How can I update and share state between both components using context?

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

const Context = React.createContext();

const Provider = ({ children }) => {
  const [value, setValue] = React.useState(0);
  return (
    <Context.Provider value={{ value, setValue }}>{children}</Context.Provider>
  );
};

const Child = () => {
  const { value, setValue } = React.useContext(Context);
  return <div onClick={() => setValue(value + 1)}>Plus plus!!</div>;
};

class Parent extends React.Component {
  render() {
    const { value, setValue } = this.context;
    return (
      <div>
        <div onPress={() => setValue(value - 1)}>MINUS MINUS!</div>
        <div>{this.props.children}</div>
        <h1>{value}</h1>
      </div>
    );
  }
}
Parent.contextType = Context;

function App() {
  return (
    <Provider>
      <Parent>
        <Child />
      </Parent>
    </Provider>
  );
}

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

https://codesandbox.io/s/thirsty-oskar-ocmxr

1 Answers

Change the "onPress" to "onClick" will work. I have tested it.

Related