Answers for "React.useContext inside class components"

2

react usecontext examples

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

// Create a Context
const NumberContext = React.createContext();
// It returns an object with 2 values:
// { Provider, Consumer }

function App() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  return (
    <NumberContext.Provider value={42}>
      <div>
        <Display />
      </div>
    </NumberContext.Provider>
  );
}

function Display() {
  // Use the Consumer to grab the value from context
  // Notice this component didn't get any props!
  return (
    <NumberContext.Consumer>
      {value => <div>The answer is {value}.</div>}
    </NumberContext.Consumer>
  );
}

ReactDOM.render(<App />, document.querySelector("#root"));



//now with useContext the same page look like this
// import useContext (or we could write React.useContext)
import React, { useContext } from 'react';

// ...

function Display() {
  const value = useContext(NumberContext);
  return <div>The answer is {value}.</div>;
}
Posted by: Guest on May-08-2021
0

React.useContext inside class components

The problem is what the error says. React hooks aren't available in class 
components. Due to differences between class components and function components,
hooks cannot be used with the former.

const SignUpScreen = ({navigation}) => {
  const { signIn } = React.useContext(AuthContext);

  return (<SignUpClass appContext={signIn}> </SignUpClass>);
}

export default SignUpScreen;

class SignUpClass extends React.Component<any> {
  constructor(props?) {
    super(props);
  }

  render() {
    return (
      <div> CounterButton: 
      	<button onClick={() => {this.props.appContext.setCount(this.props.appContext.count + 5)}}>
        	App Counter + 5
        </button>
      </div>
    )
  }
}
Posted by: Guest on September-08-2021

Code answers related to "React.useContext inside class components"

Code answers related to "Javascript"

Browse Popular Code Answers by Language