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

Different tiers of log levels

I am trying to figure out how to log only "INFO" level messages to the console for users, and to a file store "DEBUG" level posts. Currently, I have come across a solution that involves using multiple "getLogger()" functions like so: log4js.getLogger(&ap ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

Is there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

Bootstrap datepicker not applying datepicker-options as expected

I have been trying to pass all my options in a JSON file according to the instructions on http://angular-ui.github.io/bootstrap/#/top, but unfortunately, I haven't been able to get it to work. I've been experimenting with the Plunkr provided on t ...

What is the best way to retrieve URL parameters from react-router-redux in a child component?

Considering the router provided below: import React, {Component} from 'react'; import {Route, Switch} from 'react-router-dom'; import {Provider as StoreProvider} from 'react-redux'; import {ConnectedRouter} from 'react-r ...

Tips for organizing an API response based on a specific field

I'm currently in the process of learning Reactjs and I've hit a roadblock with a specific question. I have successfully fetched data using axios from an API endpoint (such as countries with details like population, currencies, region, etc.) and n ...

Troubleshooting the ineffectiveness of using the MUI onSubmit method with a

I have been using MUI for components and encountered an issue with my form not calling the onSubmit method when wrapped in the Box component. Below is a minimal example illustrating this problem. The onClick event, on the other hand, works perfectly fine ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Oops! Hardhat Test Error "Error: Virtual Machine Exception occurred while processing transaction: reverted with reason 'Please deposit additional funds'."

Encountering an issue with the following error message: Error: VM Exception while processing transaction: reverted with reason string 'deposit more' in the Hardhat Test.js file Test.js -> it("should be able to withdraw if no one appl ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

Retrieve the link of a nearby element

My goal is to create a userscript that has the following functionalities: Add a checkbox next to each hyperlink When the checkbox is clicked, change the state of the corresponding hyperlink to "visited" by changing its color from blue to violet. However ...

The TypeScript compilation is not able to find index.ts at the moment

When I tried to run 'ng serve', I encountered the following error message: The TypeScript compilation is missing node_modules/angular2-indexeddb/index.ts. It is crucial to ensure that this file is included in your tsconfig under the 'file ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

Incorporating smooth sliding animation to ng-repeat elements

Our team has developed a custom widget in ServiceNow that displays a row of icons and reveals or hides additional details in a div when icons are clicked. Below is the structure of our html and client controller: <div class="icons"> <ul class=" ...

What causes the discrepancy in CSS behavior between local and remote websites?

My chrome extension enhances facebook chatbox with jquery autocompletion. I am trying to make the suggestion list menu horizontal by modifying the jquery-ui.css. When changing display:block to display:inline, the list becomes horizontal in a local HTML fil ...

Utilizing jQuery or JavaScript to transfer information within a Bootstrap modal

I am working with a table that is generated from an SQL Table using PHP for data looping. HTML <tbody> <?php $no = 1; foreach($data_request as $data) { ?> <tr> <td class="center"><?php echo $no++.". ";?> ...

What is the process for waiting on RxJS data and how should it be retrieved?

I am faced with a situation where I need to create a user through a function, but before proceeding with the creation process, I have to verify whether another user with the same userName is already present in the session: public createUser(form: FormGroup ...

Is it possible to shift the div inline-block using the CSS :after selector?

I'm looking to adjust the placement of the disk icon so that it aligns more with the baseline of the text without increasing the vertical space between lines. Below is the CSS code I've worked on so far: .openPage:after { content: ' &a ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...

What is the best method for utilizing the CSS :target selector in order to generate a versatile modal box?

I am looking for a way to display my vast collection of proverbs from an endangered language without overcrowding the page. I have implemented a modal box solution using CSS :target selector, which expands a hidden div element when clicked on. However, I n ...