Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components.

Consider the following code:

  ${props => props.white && `color: ${colors.white}`}
  ${props => props.light && `color: ${colors.light}`}
  ${props => props.grey && `color: ${colors.grey.base}`}
  ${props => props.dark && `color: ${colors.dark}`}
  ${props => props.black && `color: ${colors.black}`}

  ${props => props.info && `color: ${colors.info}`}
  ${props => props.success && `color: ${colors.success}`}
  ${props => props.warning && `color: ${colors.warning}`}
  ${props => props.error && `color: ${colors.error}`}
  ${props => props.link && `color: ${colors.link.base}`}

This code represents a component called <Text> which alters the text color based on the prop used. For example, using <Text light> will apply the color defined as "light" in the variables file's colors object.

The code above appears repetitive as only the color name changes on each line whereas the structure remains identical.

Do you have any suggestions for making this code more concise and DRY?

Answer №1

One potential issue arises when the user includes both "white" and "black" in the props. In this scenario, it becomes unclear which color should take precedence.

${props => Object.keys(props).filter(x => colors[x]).map(y => `color: ${colors[y]}`).join(' ')}

To address this concern, the code snippet filters only those props that exist in the predefined color palette. It then applies the corresponding style text and converts the resulting array into a string using the .join method.

This solution will function correctly as long as only one prop from the color palette is passed. However, if multiple color props are included, the final color output will be determined by the last item processed by the .map function.

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

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

How come the sound is played after the command is given?

function myTimer() { randint= Math.floor(Math.random() * 10)+1; randstimuli=gorilla.stimuliURL(dict[randint]); var audio = new Audio(randstimuli); audio.play(); var start=Date.now(); var ans=prompt("was the last number the same as t ...

Ways to efficiently manage session control without repeating it in each route

I'm currently working on a Node.js application using express. I've been checking the session in every route, but now I'm looking for a way to separate this check from my routes. Any suggestions? Below is an example of one of my routes: app ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

Tips for refreshing the apollo cache

I have been pondering why updating data within the Apollo Client cache seems more challenging compared to similar libraries such as react-query. For instance, when dealing with a query involving pagination (offset and limit) and receiving an array of item ...

Can anyone assist me with this HTML/jQuery code?

Despite my efforts, I've been unable to achieve success. The challenge I'm facing is with duplicating controls for adding images. I have a button and a div where the user can choose an image by clicking the button. The selected image appears in ...

Pseudo classes in child components of React Material-UI

Can anyone assist me with adding ::after in a child element? This is the CSS code I am trying to implement: dt { float: left; } dt::after { content: ":" } I am encountering issues with my code. The ::after pseudo-element is not functioni ...

What is the reason for the disappearance of bullets on my Tailwind-styled <ul> items when overflow-scroll is added?

Currently, I am in the process of developing a website with react and tailwind. In one section of the page, I would like to incorporate a vertical scrollbar for a list. However, upon doing so, the bullets within the list disappear. This has left me puzzled ...

Is it feasible to dynamically insert and delete elements in React?

I'm currently in the process of rebuilding a project, specifically a drag and drop website builder, using React after it was originally built with a heavy reliance on jQuery. My main challenge lies in being able to dynamically add and remove elements ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Exploring Autocomplete Functionality with SQLite Integration in Flask

I have been searching for a solution to my problem without any success. My SQLite database contains electronic products, and I have a search box that allows users to search for products by typing in their name. However, I want to enhance the user experienc ...

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

Could the absence of a tree view in the div be due to an error in the positioning of the DOM

I'm currently working on displaying a tree structure with specific child elements inside a div using JavaScript and HTML. Despite creating all the necessary objects and ensuring that the data is correctly read from the JSON file (refer to the "data" i ...

Strategies for resolving the "Objects are invalid React children" issue in Next.js 13 and Next Auth

I am currently developing an application using Next JS 13 with Firebase and Next Auth. After integrating Firebase with Next Auth and utilizing the session, I encountered an error. Error: Objects are not valid as a React child (found: [object Promise]). If ...

How can I modify the icon once the accordion summary is expanded?

How can I switch the icon based on whether the accordion is expanded or not? I noticed that on the material ui page there is a CSS class called .Mui-expanded which can detect whether expanded={true} or false. But, how do I utilize this to change the ...

Issue with the _.filter function in lodash library when used in a Node.js environment

My goal is to remove rows from a CSV file that already contain email addresses found in Mailchimp. Although I attempted to achieve this with a function, it seems that the number of elements returned is not accurate: async function testDeleteEmails(listID, ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...