Vincent
Vincent

Reputation: 795

React Native - Using objects from Custom Hooks

I'm trying to get screen dimensions from a custom hook but I don't know how to use the results from the imported component.

Obviously I could use {MyDims.Width} and {MyDims.Height} to display the results but for my final script I need to use the 2 objects as strings, hence the useState().

Here is the imported component: getdimensions.js

import React, {
  useState,
  useEffect
} from "react";
import {
  Dimensions
} from "react-native";

function App(props) {

  const [Width, setWidth] = useState(0)
  const [Height, setHeight] = useState(0)

  const getDims = () => {
    setWidth(Dimensions.get("screen").width)
    setHeight(Dimensions.get("screen").height)
  }
  useEffect(() => {
    getDims()
  }, []);
    
  return {Width, Height}
}
export default App;  

And the main screen: App.js

import React, {
  useState,
  useEffect,
} from "react";
import { Text, View, StyleSheet } from 'react-native';
import useDimensions from './components/getdimensions';

export default function App() {
  
const  MyDims = useDimensions()

const [ShowMyDims, setShowMyDims] = useState({  
  width: MyDims.Width,
  height: MyDims.Height
  })

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
      width: {ShowMyDims.width} and 
     height: {ShowMyDims.height}          
      </Text>  
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: 50,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Upvotes: 1

Views: 430

Answers (1)

Prathap Reddy
Prathap Reddy

Reputation: 1739

You can return it as an array to avoid it being object. To get the updates from your custom hook to your component useState, add useEffect and trigger state updates upon change in Width, Height from your custom hook.

// In your hook component
...
return [Width, Height];

// In main component
...
const [Width, Height] = useDimensions();
const [ShowMyDims, setShowMyDims] = useState({ width: Width, height: Height });


// Add a useEffect hook to listen the updates
useEffect(() => {
  setShowMyDims({ width: Width, height: Height });
}, [Width, Height])
....

You have an option of directly using Width, Height from your custom hook into your component without having an intermediate useState.

Upvotes: 2

Related Questions