Issue
I want to pass a variable to the "shadowColor" property in my stylesheet from an array in the code above but I am getting a "Can't find name " error. I tried to use a template literal but it's not working. Any help is appreciated!
import { View, Text, StyleSheet, Image } from "react-native";
import React, { useState } from "react";
import { LinearGradient } from "expo-linear-gradient";
export default function Card(props: any) {
const colors = [
["#FE90B0", "#F45283", "#ff0047"],
["#89E5FE", "#43C5E9", "#00c9ff"],
["#AE9CFF", "#927FFC", "#2700ff"],
["#FED3A0", "#FFA741", "#ff8800"],
];
return (
<View
style={[styles.card, styles.shadow, { shadowColor: `${colors[0][2]}` }]}
>
// .... unrelated code
}
const styles = StyleSheet.create({
card: {
height: "33%",
width: "85%",
borderRadius: 35,
},
shadow: {
shadowColor: `${colors[0][2]}`,
shadowOffset: {
width: 0,
height: 18,
},
shadowOpacity: 0.25,
shadowRadius: 20.0,
elevation: 24,
},
fonts: {
padding: 15,
},
img: {
width: "100%",
height: "95%",
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
},
});
Solution
The reason this is happening is because you declare you colors
variable inside of your Card
component, but you try to use your colors
variable outside of your Card
's scope. There are several solutions, depending on what you want to do:
Lift the
colors
variable up and make it a module-scoped array:const colors = [ ["#FE90B0", "#F45283", "#ff0047"], ["#89E5FE", "#43C5E9", "#00c9ff"], ["#AE9CFF", "#927FFC", "#2700ff"], ["#FED3A0", "#FFA741", "#ff8800"], ]; export default function Card(props: any) { /* ... snip ... */ } const styles = StyleSheet.create({ /* ... snip ... */ });
Use the technique described in the question @Odunsi linked to pass the selected values into your
StyleSheet.create
call:const stylesFor = colors => StyleSheet.create({ /* ... snip ... */ }); export default function Cards(props: any) { return <View style={stylesFor(colors).SOME_CLASS} />; }
Answered By - Sean Vieira
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.