Sometimes, we want to make view 80% width of parent in React Native.
In this article, we’ll look at how to make view 80% width of parent in React Native.
How to make view 80% width of parent in React Native?
To make view 80% width of parent in React Native, we can calculate the width with JavaScript.
For instance, we write
import React, { useEffect, useState } from "react";
import { Dimensions, View, Text, StyleSheet } from "react-native";
const Comp = () => {
const [screenData, setScreenData] = useState(Dimensions.get("window").width);
useEffect(() => {
const onChange = () => {
setScreenData(Dimensions.get("window").width);
};
Dimensions.addEventListener("change", onChange);
return () => {
Dimensions.removeEventListener("change", onChange);
};
});
return (
<View style={{ width: screenData * 0.8 }]}>
<Text>hello</Text>
</View>
);
};
export default Comp;
to watch for screen dimensions change by adding the change event listener to the Dimensions object.
We call onChange with the change event is emitted by Dimensions.
In onChange, we call setScreenData set the screenData state to the screen’s width.
And we set the width of the View to screenData * 0.8.