I checked other questions and also docs but I cannot make it work. I want to pass a handler function to a child component within its props to change between themes.
I defined a state in the parent component and the handler that sets the new state. I tried with and without a parameter.
This is the parent
class MyApp extends App {
constructor(props) {
super(props);
this.state = {
colorScheme: "light"
};
this.handleColorScheme = this.handleColorScheme.bind(this);
}
handleColorScheme = scheme => {
this.setState({ colorScheme: scheme });
};
render() {
const { Component, pageProps } = this.props;
const props = {
...pageProps,
schemeHandler: this.handleColorScheme
};
return (
<Container>
<ThemeProvider
theme={this.state.colorScheme === "light" ? theme : themeDark}
>
<Component {...props} />
</ThemeProvider>
</Container>
);
}
}
export default MyApp;
And this the child component
export default function Layout(props) {
const [theme, setTheme] = useState({
palette: {
type: "light"
}
});
const toggleDarkTheme = () => {
let newPaletteType = theme.palette.type === "light" ? "dark" : "light";
props.schemeHandler(newPaletteType);
};
return (
<div>
<CssBaseline />
<div className={classes.root}>
<AppBar
position="absolute"
color={"default"}
className={classes.appBar}
>
<Toolbar>
<IconButton onClick={toggleDarkTheme}>
<Dark />
</IconButton>
</Toolbar>
</AppBar>
<main className={classes.content}>
{props.children}
</main>
</div>
</div>
);
}
When I click the button it says that toggleDarkTheme is not a function. Debugging with dev tools I see that I never reach parent function. How can this function be passed in props?
toggleDarkThemefunction in the child component