I'm writing a React Native component for a library and I want users to be able to style it using the style
property, just like React.View
and other built-in components.
However, since my component is actually made up of a few nested views, I need to do some calculations to figure out what styling to put on the inner ones. For example, I might need to adjust the sizing of an image based upon the thickness of a border around it, or adjust a highlight color based upon the given text color, or in some other way infer some piece of styling from another piece of styling.
To do this, I need to be able to extract the actual CSS properties (like borderWidth: 2
or backgroundColor: 'pink'
) out of whatever gets passed as the style
prop. This is fine as long as it comes as a plain object, but it may also be the result of a call to React.StyleSheet.create
. This seems to be an opaque object with all selectors simply mapped to numeric IDs.
How can I resolve these and get the actual CSS properties, in order to do anything more complicated with them than simply passing them straight on to a View
?
You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
To access styles of an element from React, we can assign a ref to the element that we want to get the styles for. And then we can use the window. getComputedStyle method to get the style from the element's ref.
First, you need to select the element with querySelector . Then, you use getComputedStyle to get the element's styles. If you log style , you should see an object that contains every CSS property and their respective values. You can also see this object in Chrome's and Firefox's dev tools.
The used value of a CSS property is its value after all calculations have been performed on the computed value. After the user agent has finished its calculations, every CSS property has a used value. The used values of dimensions (e.g., width , line-height ) are in pixels.
The built-in StyleSheet.flatten
function (or the identical flattenStyle
function) can turn anything that can legitimately be passed to the style
prop into an object mapping CSS property names to values. It works on plain objects, IDs returned by StyleSheet.create()
, and arrays.
Example usage to check the width specified in the style
prop from within a Component definition:
import { StyleSheet } from 'react-native'
// ... then, later, e.g. in a component's .render() method:
let width = StyleSheet.flatten(this.props.style).width;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With