Applying specific style properties in styled-components can vary based on certain conditions

Is it possible to apply multiple properties at once?

const Button = styled.div`
  color: blue;
  opacity: 0.6;
  background-color: #ccc;
`

I want to apply styles for the active state without having to specify conditions for each property individually. How can I achieve this in a more efficient way?

const Button = styled.div`
  color: ${props.active ? 'green' : 'blue'};
  opacity: ${props.active ? 1 : 0.6};
  background-color: ${props.active ? 'white' : '#ccc'};

Answer №1

Implement a functionality where two classes are created and switched based on the active property.

For instance -

CSS

.activeClass{
  color:  green;
  opacity:  1 ;
  background-color:white;
}

.inactiveClass{
  color: blue;
  opacity:  0.6;
  background-color: #ccc;
 }

Rendering logic

<button id="mybtn"  className={this.props.active ? 'activeClass' : 'inactiveClass'} >mybutton</button>

View the live demo here

Answer №2

A popular method involves conditionally rendering CSS blocks using the css API:

const first = css`
  color: red;
  opacity: 1;
  background-color: yellow;
`;

const second = css`
  color: purple;
  opacity: 0.5;
  background-color: #f0f0f0;
`;

const Box = styled.div`
  ${({ active }) => (active ? first : second)}
`;

const Section = () => {
  const [active, toggle] = useReducer(p => !p, false);
  return (
    <Box active={active} onClick={() => toggle()}>
      Click Me
    </Box>
  );
};

https://codesandbox.io/s/damp-sky-93y2d?fontsize=14&hidenavigation=1&theme=dark

Another option is to utilize common tools like swithProp from styled-tools:

import styled, { css } from "styled-components";
import { switchProp, prop } from "styled-tools";

const Button = styled.button`
  font-size: ${switchProp(prop("size", "medium"), {
    small: prop("theme.sizes.sm", "12px"),
    medium: prop("theme.sizes.md", "16px"),
    large: prop("theme.sizes.lg", "20px")
  }, prop("theme.sizes.md", "16px"))};
  ${switchProp("theme.kind", {
    light: css`
      color: LightGreen;
    `,
    dark: css`
      color: DarkGreen;
    `
  }, css`color: white;`)}
`;

<Button size="large" theme={{ kind: "light" }} />

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

Is there a way to use an Angular $watch to determine the specific changes made to $scope.value?

I am monitoring a variable called $scope.value with a watch in my code. There are two ways in which the value can be updated: The first is by updating it from the controller, such as through any services. The second way is that any input event can also ...

Integrating Facebook Videos

My website has a collection of video links that open in a fancybox when clicked using jQuery. However, there is an issue where the videos used to play with sound automatically, but now they require manual unmuting. I am unsure of why this behavior changed. ...

Guide on setting up a MEAN stack application to run on port 8080

I am brand new to the mean stack development environment. I'm attempting to configure my root domain name to display the app directory once I enter the command grunt, but the only way it currently works is at website.com:8080/!#/. How can I get it to ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Having trouble with the width:auto attribute in IE7?

CSS #wrapper .tn{ width:auto; height:20px; line-height:20px; float:left; padding:5px 2px 5px 5px; margin:0 5px 10px; font-weight:bold; background:#f0f0f0; } HTML <div id="wrapper"> ...

What is the proper way to write the code for this form?

I am exploring alternatives to using the html TABLE tag and struggling to create the desired layout. I have attached a screenshot showing my table design. How can I achieve the same layout using divs or spans while still maintaining vertical alignment of t ...

Embed one module within another module and utilize the controller from the embedded module

I am attempting to create a module and inject it into the main module. Then, I want to inject the controller into the injected module but am facing issues. In my index.html file: <html ng-app="MenuApp"> <head> </head> <body> <d ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

Experiencing an issue with Firestore returning null instead of data in JavaScript

I have created a form that, upon submission, adds a document with the data to my Firestore database. Additionally, I have set up a real-time listener on the collection where the document is added. onSubmit={async(e) => { e.preven ...

jquery-ui allowing to resize child divisions as well

Currently, I am in the process of developing a website that includes resizable divs with jQuery. However, I have encountered an issue where only the width of the child divs is being resized when I adjust them. For reference, you can view the site and its c ...

React: As soon as a character is typed, the input field immediately loses focus

Trying my hand at React development I've built a login page with email and password input fields using MUI, formik, and yup. However, I'm facing an issue where the input loses focus after entering one character. Everything else seems to be worki ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

leveraging a value in react elements

Embarking on my React journey, I have encountered new challenges. Seeking your insights to help me overcome this hurdle. My goal is to capture input values and add them to a list area. Essentially, I want to fetch state.inputValue and append it in the ul s ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Tips for minimizing the height of the Material Toolbar in Material-UI

I'm looking to customize the height of the toolbar in Material-UI to make it smaller Although I checked out How do I change the Material UI Toolbar height?, I am still struggling with this issue Increasing the height above 50 seems to work, but redu ...

Error: The property 'initializeApp' cannot be read because it is undefined

Recently, I decided to integrate Firebase libraries into my Vue project by installing them using npm install firebase. I then proceeded to add these Firebase libraries in my main.js file: import { Firebase } from 'firebase/app' import 'fir ...

Prevent users from navigating back in their browser with jQuery

As I work on developing an online testing app, one of the requirements is to prevent users from refreshing the page or going back during the test until it has ended. While I have successfully disabled the refresh action in jQuery using various methods with ...

I am looking to concatenate the existing URL with the language segment using jQuery

Looking to update the URL when clicking on a language name? Simply add the current path after the language section. For example, change the URL https://example.com/de_DE/about-us/ to https://example.com/us_EN/about-us/ and vice versa. I attempted this code ...