Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get width of an element in react native?

Tags:

react-native

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?

like image 769
木士羽 Avatar asked May 16 '16 02:05

木士羽


People also ask

How do you find the element width in React Native?

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.

How do you get width of current view in React Native?

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.

How do I get current Div width in 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.

How do you find the width and height in React Native?

state. view2LayoutProps. height + 1; const newLayout = { height: newHeight , width: width, left: x, top: y, }; this. setState({ view2LayoutProps: newLayout }); } render() { return ( <View style={styles.


1 Answers

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,
like image 173
Nader Dabit Avatar answered Oct 05 '22 23:10

Nader Dabit