Skip to content

Instantly share code, notes, and snippets.

@react-ram
Last active January 27, 2020 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save react-ram/bc4deb76af29ca536c7030751dd19d7e to your computer and use it in GitHub Desktop.
Save react-ram/bc4deb76af29ca536c7030751dd19d7e to your computer and use it in GitHub Desktop.
Context API example 1
import React from "react";
import CompoC from "./CompC";
import { UserProvider } from "./userContext";
export default function App() {
return (
<div>
<UserProvider value="ram">
<CompoC />
<CompD />
</UserProvider>
</div>
);
}
//class component
import React from "react";
import { UserContext } from "./userContext";
export default class CompC extends React.Component {
render() {
return <div>{this.context}</div>;
}
}
CompC.contextType = UserContext;
// function component
import React from "react";
import { UserConsumer } from "./userContext";
export default function CompD() {
return <div>
<UserConsumer>
{
username => {
return <h3>{username}</h3>
}
}
</UserConsumer>
</div>
import React from "react";
const UserContext = React.createContext("ramcharan");
const UserProvider = UserContext.Provider;
const UserConsumer = UserContext.Consumer;
export { UserConsumer, UserProvider };
export { UserContext };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment