Through the props and callback functions
const Parent = () = > {
const callback = (msg) = > {
console.info(msg, "msg");
};
return (
<div>
<Child callback={callback} message="Information passed to child components" />
</div>
);
};
export default Parent;
const Child = (props) = > {
const cb = (msg) = > {
return () = > {
props.callback(msg);
};
};
return <h1 onClick={cb("Information passed to parent ")}>{props.message}</h1>;
};
Copy the code
UseContext in combination with the Provider
import React, { useContext, useState } from "react";
const themes = {
light: {
foreground: "# 000000".background: "#eeeeee"
},
dark: {
foreground: "#ffffff".background: "# 222222"}};const ThemeContext = React.createContext(themes.light);
function App() {
const [theme, setTheme] = useState(themes.dark);
const toggleTheme = () = > {
setTheme((v) = > {
return v === themes.dark ? themes.light : themes.dark;
});
};
return (
<ThemeContext.Provider value={{ theme.toggleTheme}} >
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const state = useContext(ThemeContext);
console.info(state, "state");
return (
<button
onClick={state.toggleTheme}
style={{
background: state.theme.background.color: state.theme.foreground
}}
>
I am styled by theme context!
</button>
);
}
export default App;
Copy the code