Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance would be greatly 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,
  },
});

Answer №1

The issue arises because the colors variable is declared within the Card component, but it is being used outside of the scope of the Card. There are multiple ways to resolve this problem based on your requirements:

  1. Move the colors variable up and define it as 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 ... */ });
    
  2. Implement the method mentioned in the linked question @Odunsi to pass the selected values into the StyleSheet.create call:

    const stylesFor = colors => StyleSheet.create({ /* ... snip ... */ });
    export default function Cards(props: any) {
      return <View style={stylesFor(colors).SOME_CLASS} />;
    }
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoke the jquery plugin upon completion of the HTML load via Ajax

For my current project, I needed to style input radio buttons and decided to use the jquery uniform plugin. However, the radio buttons are displayed after some Ajax content is loaded onto the page. Since I do not have permission to edit the form or Ajax ...

Prepare fixtures for commands in Cypress before executing the hook

One of my main tasks is to load the fixtures file only once and ensure it is accessible across all project files. To achieve this, I created a fixtures.js file with the following content: let fixturesData; export const loadFixturesData = () => { cy ...

Issue encountered when updating npm to version 5.4.2: Unable to locate modules in ./node_modules/react-router-dom

When attempting to update my npm version from 3.10.10 to 5.4.2 and migrate react from 15.3.0 to 16.0, I deleted the node_modules folder and re-ran npm install. However, upon trying to run my application again, I encountered the following error: ERROR in ./ ...

How can Bootstrap's Collapse be activated without relying on buttons or anchor tags?

Is there a way to activate Bootstrap's Collapse feature when a user selects a Radio button, like this: <input type="radio" name="radios" value="More" data-toggle="collapse" href="#collapseExample"> <div class="collapse" id="collapseExample" ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

Automatically generate nested object properties in VueJS for streamlining code structure

Understanding the Issue I have created a custom system to monitor specific "store" properties from a JSON in a NoSQL database. The structure is fairly straightforward, with nested objects that are necessary for various reasons. The data format resembles ...

Increasing Asynchronous Capabilities with Dynamically Updating jQuery Deferred within then() Method

I am currently exploring the functionalities of jQuery Deferred and I have encountered a challenge regarding chaining multiple deferreds. Let me outline my simplified issue: var def1 = $.ajax(...); // executing ajax call 1 var def2 = null, def3 = null; $ ...

Automated playback of integrated Twitter video

Is there a way to make embedded Twitter videos autoplay? The code generates an iframe which is preventing me from using some JavaScript click tricks. Is there a workaround to enable autoplay? Plunker <script>window.twttr = (function(d, s, id) { v ...

Video margins within a webview

After numerous attempts to embed a YouTube video in a WebView, I'm still struggling with a persistent small margin on the right side of the video. I've researched similar issues and attempted to address it through JavaScript adjustments without ...

When utilizing custom modules in Node.js, is it more effective to require the module from within a function or at the top of the script?

I have developed a custom script that includes all of my common settings and functions. One specific function within this script takes a timestamp as input and outputs a human-readable date with a customized format using Moment.js. The custom script is st ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Ensuring consistent column height in HTML Tables

Hey there, I'm just starting out with CSS and I have a question about table design. I have three separate tables below and I want to ensure that all the columns in each table are of equal height. Is there an easy way to achieve this? Any suggestions o ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...

Unable to reach elements that have been loaded through ajax with jQuery

I am facing an issue where I cannot access content loaded via ajax for modification. Unfortunately, I do not have access to the js file responsible for the initial load. Therefore, I need to create a separate function to alter the content. The required mo ...

Ways to update a value in a table by comparing two JSON objects

I am currently working with two JSON files containing data as shown below: JSON 1: let classes = [{ "Class": "A", "as_of": "12/31/2020", "student": [{ "raji": { "eng": ...

Is there a missing .fillGeometry in the Figma plugin VectorNode?

The documentation for VectorNode mentions a property called fillGeometry. Contrary to this, TypeScript indicates that "property 'fillGeometry' does not exist on type 'VectorNode'". https://i.sstatic.net/ICfdw.png I seem to be missing ...

javascript: window.open()

I am currently using VB.NET 2005 and I have a requirement to launch a new browser window using Process.Start(). The challenge is that I need to specify the size of the browser window, for example, height:300 and width:500. Process.Start("firefox.exe", "ab ...

Is there a way to securely embed YouTube videos in my web application without exposing the direct video links?

I'm hoping to integrate YouTube videos into my web application, but I need a way to prevent users from accessing the direct video links while they are using the app. Does anyone have any suggestions on how this can be accomplished? I am unsure of how ...

The :after pseudo-element in action with multi-line text

Can the styling of the :after pseudo-element be applied to every line of multi-line text? Here is the code I am currently using: .container { width: 50px; } .text { position: relative; } .text:after { content: ''; position: ...