I'm trying to implement React Context feature, but for some reason I can't seem to successfully render the page. When I launch the site it just stays blank. Even though it compiles without any errors.
I have an App.js where the main code is written :
import './App.css';
import { UserProvider, useUser } from "./UserContext";
const LoggedInUser = () => {
const { user } = useUser();
return (
<p>
Hello <span className="Username">{user.name}</span>
</p>
);
};
const Header = () => {
return (
<header>
<h2>Blog App</h2>
<LoggedInUser />
</header>
);
};
const Page = () => {
const { user } = useUser();
return (
<div>
<h2>What is Lorem ipsum?</h2>
<p>
Lorem ipsum dolor sit amet...
</p>
<p>Written by {user.name}</p>
</div>
);
}
function App() {
return (
<div className="App">
<h1>hello</h1>
<Header />
<Page />
</div>
);
}
function Root() {
return (
<UserProvider>
<App />
</UserProvider>
);
}
export default Root;
Then the UserContext.js file:
import { createContext, useContext, useState } from "react";
const UserContext = createContext(undefined);
export const UserProvider = ({children}) => {
const [user] = useState({
name: "John",
email: "[email protected]",
dob: "01/01/2000"
})
return <UserContext.Provider value={{ user }}></UserContext.Provider>
}
export const useUser = () => useContext(UserContext);
And lastly index.js file, which may or may not be relevant to this issue:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
If I use export default App
instead of export default Root
and comment <Header />
and <Page />
components in the App's return the page displays hello. But if I leave export default Root
and comment <Header />
and <Page />
the hello text header disappears.
CodePudding user response:
It's because you don't pass the children
in UserContext. The code should be corrected as:
import { createContext, useContext, useState } from "react";
const UserContext = createContext(undefined);
export const UserProvider = ({children}) => {
const [user] = useState({
name: "John",
email: "[email protected]",
dob: "01/01/2000"
})
return <UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
}
export const useUser = () => useContext(UserContext);
CodePudding user response:
Your user provider isn’t rendering its children prop.
We all have those days.
EDIT: render the children prop between your UserContext.Provider tags