Home > other >  loading styles from remote json file - React Native
loading styles from remote json file - React Native

Time:10-05

I am trying to use styles / colors from a JSON file that exist on a server, so I am using useEffect function to load the style variable and pass them to stylesheet. But issue is fetching data from remote file takes some time and stylesheet doesn't load styles.

var themeStyle2 = [];
const themeStyleOnline = "https://someremote.server/theme.json";
export default function HomeScreen({ navigation }) {
     useEffect(() => {
         fetch(themeStyleOnline)
         .then((response) => response.json())
         .then((json) => themeStyle2 = json)
         .catch((error) => alert(error)).finally(() => {
             console.log("THEME STYLE >>>>>>>>>> "   themeStyle2.cardbg); 
          });
      })
}

const styles = StyleSheet.create({
  container: {
      backgroundColor: themeStyle2.background,  //style won't load 
  },
})

Above code doesn't load style because remotely loading style variables takes some time. Then I tried following method.

const themeStyleOnline = "https://someremote.server/theme.json";
export default function HomeScreen({ navigation }) {
     const [themeStyle2, setThemeStyle] = useState([]);
     useEffect(() => {
         fetch(themeStyleOnline)
         .then((response) => response.json())
         .then((json) => setThemeStyle(json))
         .catch((error) => alert(error)).finally(() => {
             console.log("THEME STYLE >>>>>>>>>> "   themeStyle2.cardbg); 
          });
      })
}

const styles = StyleSheet.create({
  container: {
      backgroundColor: themeStyle2.background,  //This Gives error themeStyle2 not found 
  },
})

What is correct way to achieve this?

Following is JSON I am trying to load.

{
   "statusbar":"#7209b7",
   "header":"#560bad",
   "headertext":"#fffffc",
   "background":"#001219",
   "cardbg":"#ffba08",
   "titlebg":"#3f37c9",
   "titletext":"#fffffc"
}

CodePudding user response:

You can’t access the theme state variable from the global scope where you are using it. I.e. the Stylesheet.create method call. You can just use the themeState in the components instead of calling in the StyleSheet.create call.

  • Related