Categories
JavaScript Answers React Native Answers

How to make dynamic styles in React Native?

Spread the love

Sometimes, we want to make dynamic styles in React Native.

In this article, we’ll look at how to make dynamic styles in React Native.

How to make dynamic styles in React Native?

To make dynamic styles in React Native, we can return style objects from functions.

For instance, we write:

import * as React from 'react';
import { Text, View } from 'react-native';
import Constants from 'expo-constants';

import { Card } from 'react-native-paper';

const createStyles = (background) => {
  return {
    borderRadius: 12,
    background,
  };
};

const App = () => {
  return (
    <View style={{ flex: 1, ...createStyles('yellow') }}>
      <Text>hello world</Text>
    </View>
  );
};
export default App;

to create the createStyles function that returns an object with some style properties.

Then we spread the returned style object into the object we set as the value of the style prop of the View.

Conclusion

To make dynamic styles in React Native, we can return style objects from functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *