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

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

In a responsive layout, a floating div refuses to adhere to the left alignment

I am working on a dynamic list using ASP:REPEATER with floating divs aligned to the left. The current layout is as follows: +---------------------+ +---------------------+ +---------------------+ | | | | | ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Restrict the dimensions of the image to fit within the div

I've been struggling to resize my LinkedIn logo on my website. I've attempted various methods, like using inherit and setting max height and width to 100%, but the logo keeps displaying at full size. Do I need to use a different type of containe ...

Storing repeated inputs in local storage multiple times

I am working on a feature where I need to store data in local storage multiple times using a dropdown menu and some input fields. Currently, I am able to retrieve all the values from the input fields and see them in the console log. My goal is to save thes ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

The tension settings in Chart.JS appear unusual

I recently updated to ChartJS v4.0.1 and noticed a new option called tension for curving the line chart. However, I'm not satisfied with how it looks. The tension option ranges from 0 to 1, and I've experimented with different values to enhance ...

The width of each column in this dataset is variable and unknown

I need to organize a varying number of items into columns. The sizes of both the items and container are unknown, as well as how many columns will fit or what width they should be. I want the browser to arrange the items in as many columns as possible with ...

Expanding the width of a Datatables within a Bootstrap modal

While working on my modal, I encountered an issue with the width of Datatables. Despite trying to adjust it to fit the modal size, it appears like this: Below is the jQuery code calling the Datatables: function retrieveTags(){ var identifier = $(&a ...

Steps on modifying the background of an element based on its location within the browser:

In the past, I've come across some impressive one-page websites with elements that would appear as you scroll. It seemed like they were created using just CSS. I think it might be achievable with the z-index and position properties? However, I can&ap ...

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

Firefox causing images to have a white border after rendering

My image (.png) has a white border only in Firefox, despite the CSS border property being set to 0. Is there a solution to remove this unwanted border around the image? ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Strategies for ensuring a promise is fulfilled before moving on to the next iteration in a never-ending for loop in JavaScript

I've been exploring ways to ensure that a promise is resolved before moving on to the next iteration in a for loop. One suggestion was to use the setInterval() function instead of a for loop, but this isn't ideal since it's hard to predict w ...

Styling elements using css and flexbox

Looking for some help with wrapping 4 items in CSS using flex. I want to display 3 items in a row, followed by a single item. .movies { display: flex; flex-direction: row; justify-content: space-between; align-items:flex-start; flex: 1 ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

What is the reason behind having several node modules directories within every project?

I'm just starting out with JS development and I have a question about the size of node modules. It seems that when many projects accumulate, we end up having to delete the node_modules folder because it takes up so much space. So, why isn't there ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

Attempting to coordinate a virtual meeting through the utilization of the Zoom API

I'm currently in the process of developing a website using Node.js, Express.js, and Mongodb. One feature I am working on is the ability for users to schedule Zoom meetings directly within the website. The desired functionality would be for users to sc ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...