2023-12-02
How to change root view background color in React Native for iOS?
Adjust background color of the root view in React Native for iOS that works with appearance changes.
Contents
- Introduction
- How to change the background color?
- Changing background color based on the current appearance
- That's all
Introduction
React Native sets the default background color of the root view to white or to systemBackgroundColor
if you are running iOS 13+. This is fine for most of the apps, but sometimes you might want to change the color to something else. In this article I will show you how to do it.
💡 systemBackgroundColor
is a new color introduced in iOS 13. It is white in light mode and black in dark mode.
How to change the background color?
First of all, let's create a new React Native project:
then cd
into your project and open the project in Xcode:
Now open AppDelegate.mm
and override following method:
💡 backgroundColor
property expects UIColor
object. You can use uicolor.io to convert hex to UIColor
initializer.
This should give you following result:
This looks great in one appearance, but what if you want to change the background color based on the current appearance? Let's say you want to have red background in light mode and blue background in dark mode.
Changing background color based on the current appearance
You can use colorWithDynamicProvider
to achieve this:
The colorWithDynamicProvider
will now listen to changes of current trait colleciton and update the background color accordingly.
This is the result:
💡 If you are using Expo, you can use the SystemUI library to achieve this but it can only set the appearance to a static color.
That's all
Thanks for reading! I hope you found this article useful. If you have any questions or feedback feel free to reach out to me on Twitter.
Huge thanks to Riccardo Cipolleschi for reviewing this article and providing valuable feedback.