GetElementById equivalent in React Native

3.1k Views Asked by At

I am working on creating a module for React-Native.

The module needs to highlight or point out certain elements on the screen based on configuration stored in a DB.

In Android, our database would consist of view ids and our code would highlight those view ids.

In HTML, the element Ids would be sufficient.

How do I define unique identifiers in React native.

These would be stored in a database and then highlighted in real-time. So the module would need to access the x, y, width and height of the elements in runtime

In HTML, I would use getElementbyId() and proceed to get its attributes. What would be the equivalent in React Native.

This works -

this.userNameRef.measure((width,height,fx,fy,px,py)=>{
        console.log(fx)
        console.log(fy)
})

If userNameRef is received as a string parameter, how can I get this data

2

There are 2 best solutions below

1
On

First of all, have in your mind, the selection within React Native is different the web.

You don't select the element directly, you must take the reference through the prop of element.

All elements in React Native has a prop called ref, you will able to have access all informations about that component, you may call the methods and get properties values.

Example using class component:

class MyComponent extends React.Component {

onEndLoadImage = () => {
    console.log(this.flatlist.current); // here have all methods and properties of Image
}

render() {
    return (
        <Image
            ref={element => this.flatlist = element}
            onLoadEnd={onEndLoadImage}
            ...
        />
    );
}

}

Example using functional components with hooks:

function MyComponent {
const imageRef = useRef(null);

const onEndLoadImage = () => {
    console.log(imageRef.current); // here have all methods and properties of Image
}

return (
    <Image
        ref={imageRef}
        onLoadEnd={onEndLoadImage}
        ...
    />
);

}

0
On

You can use onLayout props on the required View to get the view dimensions on the React Native side.

import React from "react";
import {Text, View, StyleSheet} from "react-native";

const GetLayout = (props) => {
    const _getLayout = (evt) => {
        const data = evt.nativeEvent;
        alert(JSON.stringify(data));
    }
    return(
        <View style={{flex: 1}}>
            <View style={{flex: 1}} onLayout={_getLayout}> 
                <Text>I am the required View</Text>
            </View>
        </View>
    )
}

export default GetLayout;

const styles = StyleSheet.create({

})