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

Enhancing the design of a button with whitespace using CSS

Recently, I had a well-designed landing page created using LeadPages. However, due to financial constraints, I am unable to continue paying for their services at the moment. The current landing page has proven to be effective in converting leads. https:// ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

Assistance Needed with XPATH and CSS for Selenium Automation

Can anyone assist me in finding the appropriate XPATH/CSS locator to extract text from the structure below? <div class="page-header song-wrap"> <div class="art solo-art"> <div class="meta-info"> <h1 class="page-title"> Zehnaseeb I ...

How to extract the id instead of the value in ReactJs when using Material UI Autocomplete

I am utilizing Material UI Autocomplete to retrieve a list of countries, and my objective is to capture the selected country ID in order to send it back to the database. <Autocomplete options={this.state.countries.map(option => option.name_en + ` ...

Resizable icon next to inline element caused width adjustment

I have a group of individuals listed, each with two elements side by side: a "contact me" button (an 'a' element with a fontawesome icon) and a tag displaying the user type (span element). Some users do not have a tag, and when there is one prese ...

The functionality of the `next-auth` signOut button click does not seem to accept a variable as input, although

The Nav.jsx component code provided is working as intended. In this implementation, clicking the 'Sign Out' button will redirect the application to http://localhost:3000. 'use client' import { signOut } from 'next-auth/react&apos ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

What is the best way to ensure that when a div is opened, the information to the right does not get pushed down?

I have a functioning menu bar, but when it expands, the content below is pushed down even though it should not be affected. How can I adjust my code to prevent this issue? View my website here: <div id="menu_wrapper"> <div id="menu"> &l ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Strategies for managing speed dial interactions with Material UI

I am facing an issue with my SpeedDialAction where the event of individual actions onClick is returning as undefined when I try to log it. I have experimented with using various functions as actions and also attempted arrow function syntax in the method c ...

more concise jQuery script

Currently, I am a beginner in jquery and still in the learning phase. Although my existing code is functional and achieving the desired outcome, it feels lengthy and inefficient. I am seeking a way to streamline it and make it more dynamic. Specifically, t ...

Is it possible for three.js to integrate information from REST APIs?

Currently, I am in the process of learning three.js and have successfully created basic 3D models using hardcoded values. My goal now is to retrieve these values from a database that I have set up in MSSQL Server. These x, y, and z parameters are stored ...

When attempting to render a base64 string in an <img> tag using ReactJS, an error message ERR_INVALID_URL is displayed

I am currently working on displaying server-generated images (specifically matplotlib graphs) in a ReactJS module without needing to save the files on the server. To achieve this, I decided to use base64 to create an image string. When it comes time to sh ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

I'm looking to design a button with text positioned beneath an icon using either Bootstrap 5 or CSS. How

Is there a way to create buttons like the ones shown in the examples using Bootstrap 5 or custom CSS classes? Examples: [Set of buttons][1] Notice how some of them function as dropdown buttons. I've searched for examples but most of them only show ...

Struggling to incorporate a logo into the navigation bar for an HTML project

I'm a beginner in the world of HTML and CSS, trying my hand at creating a homepage. While I managed to add a logo to the Navigation bar, it seems to have messed up the link for the HOME page. Could this be due to not wrapping the logo in a div or imp ...

What is the process for refreshing my news feed when I publish a new post?

I've developed a front-end app using react, with the backend powered by nodejs/express and typeorm/mysql. One of the features I've implemented is a clone of Twitter's "news feed" where users can post new content. Currently, after a user subm ...

What is the best way to include multiple search parameters in a Node.js URL?

I'm currently working on a project involving react, node, express, and postgress. My main challenge right now is figuring out how to use express routes to pass multiple parameters. For example: Here's the route I am trying to work with: //Get en ...

What is the best way to refresh or render a list in a React application?

While attempting to update the calendar days by using useState, I encountered a "too many re-renders" error. Even though the list was updated correctly, the component did not render on the screen as expected. I am struggling with figuring out how to update ...

What is the best way to ensure that the child element of a Material UI TableCell Component occupies the full height of the cell?

I am currently using MUI version 5 to create a table. In this table, there are two columns with cells that contain multiline TextFields. My goal is to have the TextFields completely fill the cell area. However, I am encountering an issue where when I start ...