I know how to get the theme
from components that are created using the styled
way:
const StyledView = styled.View`
color: ${({ theme }) => theme.color};
`;
But how to get from normal components or apply it for different properties? Example:
index.js
<ThemeProvider theme={{ color: 'red' }}>
<Main />
</ThemeProvider>
main.js
<View>
<Card aCustomColorProperty={GET COLOR FROM THEME HERE} />
</View>
Notice how the property that needs the theme is not called
style
Creating a HOC is a good way to tackle theming. Let me share another idea using React's Context.
Context allows you to pass data from a parent node to all it’s children. Each child may choose to get access to
context
by definingcontextTypes
in the component definition.Let's say App.js is your root.
Now our `ChildComponent.js who wants some theme and i18n strings
AnotherChild.js who only wants theme but not i18n. He might be stateless as well:
Solution I came up by now:
Create a Higher Order Component that will be responsable to get the current theme and pass as a prop to a component:
Then, call it on the component you need to access the
theme
: