Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles:

const colorPickerItem = color => (
    <View style={{backgroundColor: color.toLowerCase()}} />
)

While this approach worked well for valid CSS color strings like 'RED' and 'WHITE', I have encountered some funky color strings that are displaying as default white. Is there a way to define a default color in case the input is not a valid string color?

I came across this solution which uses new Option.style, but it seems incompatible with React Native. Are there any other suggestions or recommendations available?

Furthermore, it appears that the invalid colors contain more than one word. Considering this observation, could checking for whitespace provide an alternative solution?

Answer №1

Just a thought.

One approach that could be taken is to define a list of approved colors and verify if the color selected belongs to this list. If it does not, default to red (or any other preferred color). You can either assign the default color to a variable or store it in the first position of your approved color array for easy access as a default option.

const validColors = ['RED', 'GREEN', 'BLUE']

const isValidColor = colorToCheck => 
     validColors.some(color => color === colorToCheck) 


const colorPickerItem = color => (
    <View style={{backgroundColor: isValidColor(color) ? color.toLowerCase() : validColors[0].toLowerCase()}} />
)

Answer №2

To resolve this issue, there are a few different approaches that can be taken. One option is to compare the color against all valid color keywords, which is the most straightforward solution. However, if you simply want to set a default color when the comparison fails, there is an easier alternative.

Utilize CSS by adding a className like so:

<View className='defaultcolorfallback'/>

Then, include the following in your css file:

.defaultcolorfallback {
  background-color: #123456;
}

When the specified background-color fails, it will automatically default to the set background-color.

If you prefer not to modify your css and don't mind resorting to a slightly unconventional method, try the following approach:

<View style={{background: '#123456', backgroundColor: color.toLowerCase()}} />

Although it may not be the most aesthetically pleasing solution, it does effectively address the issue at hand!

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

Having trouble installing expo-cli using npm on your Ubuntu OS?

$ sudo npm install -g expo-cli [sudo] password for maky: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/[email protected] (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin): npm WARN notsup SKIPPING OPTIONAL ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

Creating a User-friendly Layout for Admin Pages in Next.js Version 13

Hey there, I'm facing an issue with the layout while using Next.js 13 Experimental App Directory. On my website's index page or routes '/', I want to show a landing page and use a specific layout for all pages except for those under the ...

Is it possible to target the initial sibling of a parent element using a CSS selector?

Is there a way to target the <p> element using only the id "Standort" as a constant? Any suggestions on how to accomplish this? <section> <header> <h2 class="licht"><span id="Standort" class="-sitemap-select-item-select ...

If the checkbox is selected, the textbox will receive the class "form-input validate required" upon Jquery validation

I am using Jquery Validation plugin to validate a form on my website. Below is the HTML form code: <form id="caller"> <label>Phone:</label> <input type="text" name="phone" id="phonen" class="form-input" value="" /> <di ...

Exploring methods to deactivate specific dates within the angular material datepicker

Is it possible to prevent specific dates from being selected based on the current date? For example, if today is 8/1/16, I would like to disable the next 4 days (any number of days could be chosen), excluding weekends. So, if today is 8/1/16, I would want ...

Customizing Material-UI elements in React using CSS styling

My goal is to style all the <Chip> elements within a <Grid> that has the class .table-header, but they are not changing their style (I have a <p> that should be colored in red and it works). Why does the styling work for the <p> ele ...

Integrating custom non-NPM JavaScript files into Angular 2

Currently, the application I am working on is running in an environment with angular 2.0.0 final using typescript and also utilizes angular-cli 1.0.0-beta.15. Since the development of the application involves multiple developers who all use typescript, I ...

Learn how to fetch JSON data from an API and populate a list in React.Js

I'm having trouble fetching data from an API in React.Js due to a small issue with the componentDidMount function. Here is the API: I've tested this code with other APIs successfully, but for some reason it's not working with this one. I&a ...

Vue(x) causing state mutation in array

I'm currently in the process of building a Vue application to help me learn more about web development. I've hit a roadblock when it comes to updating an array in my state with data from an API. Here's a snippet of the API response: { "st ...

Maintaining the style of `li` elements within a `ul` list while ensuring they all

Struggling to create a menu list item with 4 items that won't fit on one line? Nested divs didn't work when adding padding. Here is my latest HTML and CSS: HTML: <div id="header"> <ul id="menu"> <li><a href="#"& ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

Unlocking the Power of JSON Rendering in React

There is a JSON object containing random numbers. Initially, the object is empty but it gets updated through props. summary: { numbers: {"123": 45,"678": 9,"101": 11}, other-stuff: "some other stuff" } The goal is to display the numbers in the fo ...

Difficulty arises when trying to deploy a React application on a stationary Nginx server

I'm encountering issues trying to deploy my React app on a remote server. My Nginx configuration looks like this: server { listen 80; listen [::]:80; server_name xxx.xxx.x.x; root /var/www/my-site; inde ...

Issue with October CMS: Radio button selection triggers an Ajax call, but clicking twice in quick succession causes the content

I am currently utilizing October CMS and materializecss to develop a form with options on one of my pages. The form functions correctly as it dynamically loads content when different options are clicked. However, I have identified a problem where clicking ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

I am experiencing difficulty transferring the files to my API by using multer

For my car listing project, I am trying to set up a photo upload system. This is my first time using multer and I can't seem to figure out what's going wrong. I've done research, checked tutorials, and reviewed the documentation before reach ...

What is the best way to adapt a wavetable for compatibility with the `OscillatorNode.setPeriodicWave` function?

I am exploring the use of a custom waveform with a WebAudio OscillatorNode. While I have basic programming skills, I am struggling with the mathematical aspects of audio synthesis. Waveforms are essentially functions, which means I can sample them. Howeve ...