'Components into React Context Provider don't get props?
I got a little question about context and props I got a very simple App that only change background color when you hit checkbox.
Here I got my App.js
function App() {
const [colorMode, dispatchColor] = React.useReducer(colorReducer, themes.light);
const theme = colorMode;
return (
<div>
<ThemeContext.Provider value={theme}>
<CheckBox colorMode={colorMode.dark} onChangess={() => dispatchColor({ type: 'dark' })} colorName="dark" />
<CheckBox onChangess={() => dispatchColor({ type: 'light' })} colorName="light" />
<CheckBox onChangess={() => dispatchColor({ type: 'rosee' })} colorName="rosee" />
<Toolbar />
</ThemeContext.Provider>
</div>
)
}
export default App
My CheckBox Component :
function CheckBox({ colorMode, onChangess, colorName }) {
const theme = React.useContext(ThemeContext);
console.log('COLOR MODE:', colorMode) //return undefined I don't know why :S
const handleCheck = e => {
onChangess(e.target.checked)
}
return (
<label style={{ background: theme.background, color: theme.foreground }}>
<input type="checkbox" checked={theme.name === colorName} onChange={handleCheck} />{' '}
utiliser le {colorName}
</label>
)
}
A little reducer :
const colorReducer = (state, action) => {
switch (action.type) {
case 'dark':
return { ...themes.dark };
case 'light':
return { ...themes.light };
case 'rosee':
return { ...themes.rosee };
default:
throw new Error("action non supportée");
}
}
And my Theme Object :
const themes = {
light: {
name: 'light',
ul: { listStyleType: 'square' },
li: { background: '#eeeeee', color: '#000000' },
foreground: '#000000',
background: '#eeeeee',
},
dark: {
name: 'dark',
ul: { listStyleImage: "url('https://www.w3schools.com/css/sqpurple.gif')" },
li: { background: '#222222', color: 'white' },
foreground: '#ffffff',
background: '#222222',
},
rosee: {
name: 'rosee',
ul: { listStyleImage: "url('https://www.w3schools.com/css/sqpurple.gif')" },
li: { background: '#440536', color: 'white' },
foreground: '#e918aa',
background: '#531345',
},
}
In my checkBox Component, => I got a colorMode props, which I'm passing colorMode.dark value.
When I try to check or console.log that props value into my CheckBox component, I got an undefined value (even with useLayoutEffect).
But if I try to check my "colorMode" object into the App Component : I can see it !. Some could explain me why ? I try to figured out on google but don't find answers.
I don't know if its clear, I hope so.
Thanks for you help, I'm a student.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
