How get width of an element in react native such as View ? As there is not percent usage for width in react native, how to get width of an element or parent element?
To get the width of an Element using a ref in React: Set the ref prop on the element. In the useLayoutEffect hook, update the state variable for the width. Use the offsetWidth property to get the width of the element.
To get the size of a View in React Native, we can get them from the parameter of the onLayout callback. For instance, we write: import * as React from 'react'; import { View, StyleSheet } from 'react-native'; import { Text } from 'react-native-paper'; const MyComponent = () => { const [dims, setDims] = React.
To get the width of an element in a React component, we can assign a ref to the element we want to get the width of. Then we can use the offsetWidth property to get the width. to add the ref with the useRef hook. Then we pass ref as the value of the ref prop to assign the ref to the div.
state. view2LayoutProps. height + 1; const newLayout = { height: newHeight , width: width, left: x, top: y, }; this. setState({ view2LayoutProps: newLayout }); } render() { return ( <View style={styles.
You can call the onLayout
event to measure an element:
measureView(event) {
console.log('event properties: ', event);
console.log('width: ', event.nativeEvent.layout.width)
}
<View onLayout={(event) => this.measureView(event)}>
As far as percentage width and height, you can get the window width and height and use them like this:
var {
...
Dimensions
} = React
const width = Dimensions.get('window').width
const height = Dimensions.get('window').height
// 80% width
width: width * .8,
// 25% height
height: height / 4,
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