Search code examples
javascriptreactjsreact-nativeuse-statereact-native-stylesheet

React Native - unable to pass state variable into style


My code fetches a json file, calculates a value and I want to pass this value into the style of TouchableOpacity. Below is my attempt:

const [height, setHeight] = useState(0)
const [isLoading, setLoader] = useState(true)

const fetching = async () => {
    ...//code that fetches the value
    setHeight(value)
    setLoader(false)
} 

if (isLoading) {
    return (
        <Text> Loading...</Text>
    )
}

return (
    <View>
        <TouchableOpacity
              style={{height: height, width:30, backgroundColor: "red" }} />
         ... //other parts of the return statement 
    </View>

)

the complete code:

<View style={{height: height}}>
     <TouchableOpacity
          style={{width:30, borderWidth:5, marginTop:20, backgroundColor:"blue", height:height}}>
     </TouchableOpacity>
</View>

Any help would be appreciated.


Solution

  • I think your useState is fine. However either the parent View doesn't have any space or the TouchableOpacity has nothing to display.

    You can try to do:

    return (
        <View>
            <TouchableOpacity
                  style={{height, width:30, borderWidth: 5 }} />
             ... //other parts of the return statement 
        </View>
    )
    

    If you see no border, then it's a problem with the parent View

    You can then try:

    return (
        <View style={{flex: 1}}>
            <TouchableOpacity
                  style={{height, width:30, borderWidth: 5 }} />
             ... //other parts of the return statement 
        </View>
    )
    

    You could also try adding a Text component with some text to the TouchableOpacity.

    This code:

    import React, { useEffect, useState } from 'react';
    import {Text, View, TouchableOpacity} from 'react-native';
    
    export default function App() {
      const [height, setHeight] = useState(0)
      const [isLoading, setLoader] = useState(true)
    
      useEffect(() => {
        const timerTask = setInterval(() => {
          setHeight(Math.random() * 200)
          setLoader(false);
        }, 5000);
        return () => clearInterval(timerTask);
      }, [])
    
      if (isLoading) {
        return (
          <Text> Loading...</Text>
        )
      }
    
      return (
        <View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <TouchableOpacity
            style={{width: 30, borderWidth: 5, marginTop: 20, backgroundColor: "blue", height}}>
          </TouchableOpacity>
        </View>
      )
    }
    

    Produces a blue touchable opacity that changes height every 5 seconds. Also when I touch it, it turns a lighter shade.