Reputation: 3600
<ThemeContext.Consumer>
{({theme, toggleTheme}) => (
<button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
I got the above code from here.
Is there an alternative way of writing the second line? The curly brackets mixed with parentheses is kind of weird in my opinion, and I'd like to know if there's an alternative way of writing it.
Upvotes: 2
Views: 55
Reputation: 5657
You can use useContext
hook, which lets you read the context and subscribe to its changes, and which is really convenient when you want to subscribe to the changes of multiple contexts:
function ThemeTogglerButton() {
const { theme, toggleTheme } = useContext(ThemeContext);
const { ... } = useContext(AnotherContext);
return (
<button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
);
}
The second approach is to create an HOC, which lets you inject the context as props to your components:
withTheme.jsx (HOC) :
export const withTheme = Component => props => (
<ThemeContext.Consumer>
{contextProps => <Component {...props} {...contextProps} />}
</ThemeContext.Consumer>
);
ThemeTogglerButton.jsx:
import { withTheme } from "./withTheme"
const ThemeTogglerButton = ({ theme, toggleTheme }) => {
return (
<button onClick={toggleTheme} style={{ backgroundColor: theme.background }}>
Toggle Theme
</button>
);
}
export default withTheme(ThemeTogglerButton);
App.jsx:
import ThemeTogglerButton from "./ThemeTogglerButton";
const App = () => (
<ThemeContext.Provider value={...}>
<ThemeTogglerButton />
</ThemeContext.Provider>
)
Upvotes: 4