Skip to content

Instantly share code, notes, and snippets.

@Mayankgupta688
Created January 15, 2020 10:54
Show Gist options
  • Save Mayankgupta688/b92ddd7602a7de31c2333a88baf2a3fa to your computer and use it in GitHub Desktop.
Save Mayankgupta688/b92ddd7602a7de31c2333a88baf2a3fa to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
var userDetailContext = React.createContext(null);
export default function UserDetailsComponent() {
var [userDetails] = useState({
name: "Mayank",
age: 30
});
return (
<userDetailContext.Provider value={userDetails}>
<h1>This is the Parent Component</h1>
<hr />
<ChildComponent userDetails={userDetails} />
</userDetailContext.Provider>
);
}
function ChildComponent(props) {
return (
<div>
<h2>This is Child Component</h2>
<hr />
<SubChildComponent />
</div>
);
}
function SubChildComponent(props) {
var contextData = React.useContext(userDetailContext);
return (
<div>
<h3>This is Sub Child Component</h3>
<h4>User Name: {contextData.name}</h4>
<h4>User Age: {contextData.age}</h4>
</div>
);
}
@chhatarshal
Copy link

You created all parent child components in single file because of this userDetailContext is available to all child component what if child component is in another file. How will I get userDetailContext there ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment