When utilizing the "as" attribute, styled components do not inherit any styles

I am currently utilizing both styled-system and styled components, working on a simple scenario like the one below:

const buttonFont = {
  fontFamily: "Chilanka"
};

// define basic text styling
const Text = styled.div`
  ${typography}
  ${color}
`;

// create button component
const Button = ({ children, ...rest }) => {
  return (
    <Text as="button" {...buttonFont } {...rest}>
      {children}
    </Text>
  );
};

// style button using custom styles
const StyledButton = styled(Button)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

// Issue arises with inheriting styles when changing tag to label
const StyledLabel = styled(StyledButton).attrs({
  as: "label"
})``;

The goal is to have a StyledLabel component that inherits all styles from StyledButton, but switches the HTML tag to label. However, when using the "as" attribute, the StyledLabel does not retain the buttonFont styles.

To see a live demonstration, please visit the following link: demo

Answer №1

Not entirely certain what your ultimate objective is, but these 2 instances proved effective in terms of inheritance. Although, they may not align with your composition strategy:

import React from "react";
import styled, {css} from "styled-components";
import { typography, color } from "styled-system";
import ReactDOM from "react-dom";

import "./styles.css";

const buttonFont = {
  fontFamily: "Chilanka"
};

const Text = styled.div`
  ${typography}
  ${color}
  margin: 24px;
`;

const StyledButton = styled(Text)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

const StyledLabel = styled(StyledButton)`
  color: yellow;
`;

const __Text = styled.div`
  ${typography(buttonFont)}
  ${color}
  margin: 24px;
`;

const __StyledButton = styled(__Text)`
  color: white;
  background-color: gray;
  padding: 10px 20px;
  border: 2px solid black;
`;

const __StyledLabel = styled(__StyledButton)`
  color: yellow;
`;

function App() {
  return (
    <div className="App">
      <StyledButton as="button" {...buttonFont}>styled button</StyledButton>
      <StyledLabel as="label" {...buttonFont}>Does inherit styled font with "as"</StyledLabel>
      <br />
      <br />
      <br />
      <__StyledButton as="button">styled button</__StyledButton>
      <__StyledLabel as="label">Does inherit styled font with "as"</__StyledLabel>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

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

Stop SCSS from processing CSS variables in Angular-CLI

I am currently using Angular5 with sass v1.3.2. My goal is to dynamically change a color that is widely used in the scss files of my single page app without having to recompile new files. This color is globally defined in my _variables.css as: $brand: # ...

Every time I click a button, I am trying to add JSON objects into an array and then show the outcomes

Currently, my goal is to create a random selection feature from an array that users can contribute to by clicking a button. I am a bit unsure about how to proceed with this task. The application is developed in React and it utilizes the movieDB's API ...

Is it possible to set the radius of a d3.js circle using a style attribute?

Learn more about styling in d3.js with this detailed guide that explains how style attributes can be leveraged to customize the look of a circle, including fill color, stroke color, and stroke width. Is it possible to adjust the radius of a d3.js circle u ...

Having trouble with positioning divs on top of each other? Struggling to get position absolute to work correctly?

Currently, I am utilizing flexbox to construct a grid layout. However, I have hit a roadblock when attempting to make the divs stack on top of each other. The overflow:auto is hidden and position relative has been added to the carddiv. While the divs are s ...

Tips for optimizing the page speed of your Pixi JS app by ensuring it runs efficiently after the page loads

On my website, I implemented a dynamic gradient animation with shape-changing blobs using pixi js. The animation functions flawlessly, but the issue arises when I run page speed tests - the test assumes that the page has not finished rendering because the ...

Adjust padding of radio button labels in Qualtrics for a cleaner, more streamlined appearance

As I delve into the world of CSS, my goal is to customize the existing survey theme known as "Minimal 2014". Specifically, my focus is on minimizing the spacing in various areas to create a more compact design. So far, I've successfully reduced the g ...

Retrieving Data from Class Component in a Functional Component using React

I am currently utilizing a React module called react-semantic-ui-datepickers, which I believe is built upon react-datepicker. Nonetheless, this is more of a general React query. In my file, I have both my main class component and the date picker functional ...

Cover the entire section with an image

I'm aiming to achieve a similar layout like this (using tailwind) : https://i.stack.imgur.com/G0oti.png Here's the current setup: <section class="bg-juli-white pt-24"> <div class="max-w-6xl mx-auto flex flex-col" ...

The hover drop-down menu in CSS is not appearing in the correct position

Having trouble with my navigation bar - the dropdown menu isn't showing up below the category when I hover over it. It keeps ending up in the left-hand corner and I can't access it! I've searched everywhere for a solution, but can't fin ...

Tips for enhancing a TypeScript interface for a React component in (Material-UI) by utilizing styled-components

I've been struggling to find a solution for this overload issue with no luck so far. My stack includes Typescript, Styled-components, and Material-UI. I am utilizing styled(MUIButton) to extend the default Button from MUI. While my props are being pas ...

The mobile devices do not display minuscule text when rendering the React responsive UI

Recently, I decided to experiment with the responsive drawer feature of React Material UI. To try it out, you can access the online demo through the Code Sandbox link provided in the official documentation. To begin my testing, I copied and pasted the cod ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

What is the best way to display breadcrumb text on a new line within a pop up when the width exceeds without resorting to a scroll bar

Presently, my breadcrumb has a scrollable wrap with text overflow I want to make the overflowed text continue on the next line. How can I achieve this? The CSS code I am using for the image attached is as follows: .breadcrumb-css { text-overflow: ellip ...

Using `then` is functioning properly, however, `await` is not compatible with Promises from thunk

I am currently working with redux/toolkit and have a thunk action in place to make an API update request followed by navigation. I attempted to return a promise in order to wait for the operation to finish before proceeding with navigation. The problem a ...

"Double the fun with fullcalendar.io - where every event is doubled

I am currently using a combination of rails and react.js for my latest project. Let's say I create event A, but then have a change of heart and decide to cancel it via a bootstrap modal. Afterward, I start another event B and proceed to confirm it, ho ...

The default expansion behavior of Google Material's ExpansionPanel for ReactJS is not working as expected

Currently, I am in the process of developing a ReactJS application that utilizes Google's Material-UI. Within this project, there is a child class that gets displayed within a Grid once a search has been submitted. Depending on the type of search con ...

Setting a fixed width for the body element results in alignment problems

I'm struggling with aligning divs properly on my HTML page that has a tab using CSS and jQuery. Whenever I try to set a fixed width for the body or main container, everything goes out of place... How can I ensure that the body has a minimum fixed widt ...

Guide on transmitting data between NextJS and MongoDB

I'm facing an issue where the data from a form is being sent to MongoDB as undefined using nextJS and MongoDB. NewPlayerPage component: const newPlayerPage = (props) => { console.log('props: ' + props); const handleAddPlayer = a ...

Is there a way to create animated CSS box-shadow depth using jQuery or CSS3 transitions?

This code snippet applies delays but doesn't seem to update the style changes until the loop completes: for (i=20;i>=0;i--) { var boxShadow = i+"px "+i+"px "+i+"px #888"; $('article').css("box-shadow", boxShadow); ...

Using CSS to Create a Background with RGBA Color and Image

Having an issue with my CSS. I'm trying to create a scrolling background for the left section of my website. The RGBA is currently overlapping the entire page, but I only want it to overlap the background image. The same goes for the gridtile (the ov ...