Example 1.5
Wed May 15 2024 10:24:16 GMT+0000 (Coordinated Universal Time)
Saved by
@beyza
import React, { useContext, createContext } from 'react';
// Step 1: Create a context with createContext()
const ThemeContext = createContext();
// Step 2: Create a ThemedComponent to consume the theme value
function ThemedComponent() {
// Step 3: Use useContext hook to consume the theme value from the context
const theme = useContext(ThemeContext);
return (
<div style={{ backgroundColor: theme.background, color: theme.text }}>
<h2>Themed Component</h2>
<p>This component consumes the theme value from the context.</p>
</div>
);
}
// Step 4: Wrap the ThemedComponent with ThemeContext.Provider in the App component
function App() {
const themeValue = {
background: 'lightblue',
text: 'black'
};
return (
<div>
<h1>App Component</h1>
{/* Provide the value of the theme */}
<ThemeContext.Provider value={themeValue}>
{/* ThemedComponent is wrapped with ThemeContext.Provider */}
<ThemedComponent />
</ThemeContext.Provider>
</div>
);
}
export default App;
content_copyCOPY
https://chatgpt.com/c/3e4f5a44-577a-4ca4-970d-80b8a2a76efa
Comments