Last active
January 27, 2020 17:28
-
-
Save react-ram/bc4deb76af29ca536c7030751dd19d7e to your computer and use it in GitHub Desktop.
Context API example 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function component | |
import React from "react"; | |
import { UserConsumer } from "./userContext"; | |
export default function CompD() { | |
return <div> | |
<UserConsumer> | |
{ | |
username => { | |
return <h3>{username}</h3> | |
} | |
} | |
</UserConsumer> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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