ThemeProvider
The previous solution works great for only one component, but imagine having to do this for every component you want custom styles for. That could get a bit tedious to manage. Thankfully, there's a better way to do this. React Native Elements ships with a 3 utilities for large-scale theming.
Firstly you'll want to set up your ThemeProvider
.
import { ThemeProvider, Button, createTheme } from '@rneui/themed';
const theme = createTheme({
Button: {
raised: true,
},
});
// Your App
const App = () => {
return (
<ThemeProvider theme={theme}>
<Button title="My Button" />
<Button title="My 2nd Button" />
</ThemeProvider>
);
};
The example above achieves the same goals as the first example — apply the same
styles to multiple instances of Button
in the app. However this example
applies the raised
prop to every instance of Button
inside the component
tree under ThemeProvider
. Both of these buttons will have the raised
prop
set to true.
This is extremely convenient and is made possible through React's Context API.
Light and dark mode
React Native Elements also provides a preset dark mode palette to get you started with using dark mode in your app.
Use the prop mode
in createTheme
to set the default dark theme. You may want to set this by using a button,
or by using the user's configured settings
import { ThemeProvider, Button, createTheme } from '@rneui/themed';
const myTheme = createTheme({
lightColors: {
primary: '#f2f2f2',
},
darkColors: {
primary: '#121212',
},
mode: 'dark',
});
// Your App
const App = () => {
return (
<ThemeProvider theme={myTheme}>
<Button title="My Button" />
</ThemeProvider>
);
};
But how to switch modes?
import { useTheme } from '@rneui/themed';
const App = () => {
const { updateTheme } = useTheme();
const switchToDarkMode = () => {
updateTheme({
mode: 'dark',
});
};
const toggleTheme = () => {
updateTheme((theme) => ({
mode: theme.mode === 'light' ? 'dark' : 'light',
}));
};
return (
<>
<Button title="Toggle Theme" onPress={toggleTheme} />
<Button title="Dark" onPress={switchToDarkMode} />
</>
);
};
const theme = createTheme({
Text: (prop) => ({
style: prop.h5 && { fontSize: 8 },
}),
});
const theme = createTheme({
Text: {
h5Style: { fontSize: 8 },
},
});