Combine one CSS property in Emotion

Having some trouble creating reusable animations with Emotion. I've defined a fadeUp animation that works well:

export const animatedFadeUp = css`
  opacity: 1;
  transform: translateY(0);
`;

export const fadeUp = css`
  opacity: 0;
  transform: translateY(var(--spacing-medium));
  transition: opacity 0.5s ease-in-out,
    transform 0.5s ease-in-out;

  html.no-js & {
    ${animatedFadeUp}
  }
`;

However, when applying the fadeUp animation to an element already with its own transitions, it gets overridden. Like in the case of this button:

const Button = styled.button`
  ${fadeUp}
  background: orange;
  transition: background-color 0.5s ease-in-out;

  &:hover,
  &:focus {
    background: gold;
  }
`;

Is there a way to combine only one property? Perhaps like this:

const Button = styled.button`
  ${fadeUp}
  background: orange;
  transition: ${fadeUp.transition},
    background-color 0.5s ease-in-out;

  &:hover,
  &:focus {
    background: gold;
  }
`;

Answer №1

Instead of utilizing CSS tagged template literals or styled components, consider using it as a CSS object. This approach offers more flexibility and makes it easier to reference their properties.

<p
  css={{
    color: 'red'
 }}
>Hello World</p>

Your code would then look like this:

export const animatedFadeUp = {
  opacity: 1,
  transform: 'translateY(0)',
};

export const fadeUp = {
  opacity: 0,
  transform: 'translateY(var(--spacing-medium))',
  transition: `opacity 0.5s ease-in-out,
    transform 0.5s ease-in-out`,

  ['html.no-js &']: {
    ...animatedFadeUp
  }
};

const App = () => (
  <button
    css={{
      ...fadeUp,
      background: 'orange',
      transition: `${fadeUp.transition},
        background-color 0.5s ease-in-out`,

      ['&:hover']: {
        background: 'gold',
      },
      ['&:focus']: {
        background: 'gold',
      }
    }}
  >Click Me</button>
)

Answer №2

Unfamiliar with the Emotion library, it is possible that an API exists allowing access to style values like ${fadeUp.transition}. However, if such an API does not exist, it may enhance the complexity of the library. Nevertheless, there is still hope to solve this issue using javascript language features without extensive knowledge of the API. Here is an example:

import React, { useState } from 'react';
import styled from '@emotion/styled';
import { css } from '@emotion/react';

export const animatedFadeUp = css`
  opacity: 1;
  transform: translateY(0);
`;

// A function is invoked immediately to obtain an object with properties `css` and `transition`
export const fadeUp = (() => {
  const transition = 'opacity 0.5s ease-in-out, transform 0.5s ease-in-out';

  return {
    css: css`
      opacity: 0;
      transform: translateY(25px);
      transition: ${transition};

      &.active {
        ${animatedFadeUp}
      }
    `,
    transition,
  };
})();

const Button = styled.button`
  ${fadeUp.css}
  background: green;
  transition: ${fadeUp.transition}, background-color 0.5s ease-in-out;

  &:hover,
  &:focus,
  &.active {
    background: gold;
  }
`;

function App() {
  const [className, setClassName] = useState('');

  return (
    <div className="App">
      <Button className={className}>This my button component.</Button>

      <button onClick={() => setClassName(className ? '' : 'active')}>
        Toggle
      </button>
    </div>
  );
}

export default App;

To summarize, we create an object containing information about the css and transition for future use. One drawback of this method is the need to specifically access fadeUp.css when using fadeUp, unlike other css created by emotion.

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

The PhoneInputWithCountry component does not accept value changes through events

My current project involves utilizing the PhoneInputWithCountry component from react-phone-number-input within Next.js 14. I am facing an issue where I need to automatically set a value in the PhoneInputWithCountry component when the user interacts with a ...

Tips for indicating which content to display on template literals

Utilizing template literals to showcase some fetched data, I've successfully displayed all the necessary information on the frontend. However, certain content is hidden and meant to be toggleable. Yet, I'm struggling to figure out how to link eac ...

Transform your image using the Bootstrap framework

I am attempting to create a similar banner using bootstrap. You can view the demo of the banner here. https://i.stack.imgur.com/JXLNY.png I'm struggling to understand how to achieve this in bootstrap 3 and where to begin. Should I use rows and colum ...

the present time plus a one-hour situation

I am facing a challenge where I need to dynamically adjust the path based on specific time conditions. In this situation, I will be working with two date variables retrieved from an API: CheckInStartDate and CheckInEndDate. The current system date and tim ...

I prefer my information to be arranged neatly and separated by spaces

Is there a way to display data neatly formatted with space between each entry? I'm not sure why id one is not being selected I prefer using the append method so I can dynamically add content later on How can I organize data into two columns, wit ...

Attempting to send a request from the front-end to the back-end is resulting in a 404 endpoint error

I encountered an issue while sending a post request from the front end to the backend. The error message I received was: " Error: Request failed with status code 404 " " Had Issues POSTing to the backend, endpoint " My main concern is ...

Modifying only specific state value in react-redux using the useDispatch function

Currently, I am implementing Google OAuth for authentication in a NextJS project using next-auth. Upon login, I store the user's name and email in the state. However, the issue arises when I attempt to update only these two fields within the state obj ...

How to extract various elements from a database array by utilizing .map within a React Component?

I'm currently diving into React and have encountered a challenge when it comes to rendering multiple elements simultaneously. The issue revolves around fetching an Array from Firebase, which is supposed to generate a new div and svg for each item in ...

Is there a way to control the visibility of a bootstrap spinner using jQuery?

One challenge I'm facing is displaying a bootstrap spinner once a button is clicked and then hiding it once a response is received from an API, essentially indicating a loading status. The structure of my button is as follows: <div class="col-6"& ...

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

Adding new fonts to an Angular 2 web page

I am working on an Angular 2 application and I want to incorporate wrapbootstrap. However, I am facing an issue with the fonts (bootstrap, font-awesome, google) and I am not sure how to include them. While using the css file for wrapbootstrap, I am gettin ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

Encrypting data using NodeJS Crypto and decrypting it in front-end JavaScript

I'm currently on the hunt for a way to perform AES256 CBC decryption on the client side. When working with nodeJS, I typically utilize this function for encryption: exports.encrypt = function(txt, cryptkey){ var cipher = crypto.createCipher(' ...

Define URL parameters within the ngResource framework

My current setup involves utilizing ngResource in my service to retrieve comments for specific news posts within my web application. However, I am facing an issue where the query for comments for a particular news post, article.comments = commentService.q ...

Is there a way to move the Autocomplete placeholder to a new line?

When using Autocomplete from material-ui, I encountered an issue where the list of selected values and the placeholder were in the same line. I wanted to display the placeholder on a new line but couldn't find a way to do so. Although I could change t ...

Setting the state object dynamically in React by using a variable name as an argument

I'm faced with a situation where I need to send a list of state object variables and dynamically set them inside the setState function using the provided variable. I have one main setState function that will receive these state variables and set them ...

What is the best way to display data from an object with changing properties in React.js?

Dealing with dynamic properties in an object can be tricky, especially when trying to output the data. I encountered this issue while working with an array of objects fetched from an API call. The array contains an object named languages, and its key value ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

Is there a method to retrieve the data type along with the data using Sequelize?

Can someone help me retrieve both the data type and data of an attribute using axios and sequelize? ...

There seems to be an issue with the functionality of updating and creating in Kendo

While the grid is reading rows correctly, encountering issues with updating and creating data. The controller doesn't seem to be invoked at all. Kindly review the provided code to identify any errors. The JSON response from the read webservice is ...