Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another.

While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component references another.

So my specific question is: in the scenario below - do references ${A}, ${B} apply their styles to the wrapper element? Or do they only modify certain attributes?

What happens behind the scenes in this situation?

For instance:

const A = styled.div`
    background-color: red;
    margin-top: 10px;
`

const B = styled.div`
    background-color: blue;
`

const Wrapper = styled.div`
    ${A}, ${B} {
        background-color: green;
    }
`
export const NiceComponent: React.FC = () => {
    return (
        <Wrapper>
            <A />
            <B />
        </Wrapper>
    );

Answer №1

When referencing other styled components (such as A and B) as interpolation within the pseudo-SCSS string template of a styled component (in this case Wrapper), it is like using their automatically assigned class names within your selector.

This allows you to target either ancestors (as shown in the documentation) or children (like in your example).

It's important to note that this technique does not "pass styling"; to achieve that, you would need to style another styled component, similar to inheritance (for example, by using const Child = styled(A)).

In your scenario, styled-components will assign a class name to each component; let's say "scAAA" for component A, and "scBBB" for B. Therefore, the following code:

const Wrapper = styled.div`
    ${A}, ${B} {
        background-color: green;
    }
`

...is essentially equivalent to:

const Wrapper = styled.div`
    .scAAA, .scBBB {
        background-color: green;
    }
`

This means that a new background color is applied to all instances of components A and B which are descendants of Wrapper.

However, if you use them outside of Wrapper, they will retain their original styles only.

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 it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

What could be causing the issue with updating a js file using ajax?

I've been dealing with a php file called users. Initially, everything was going smoothly as I wrote some JavaScript code for it. However, after making updates to the JavaScript code, it seems to have stopped functioning. Below is the content of the p ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

Mentioning VARs found on additional pages

I'm currently designing a website. At the moment, I have set up the site to prompt users for their name on the landing page and store it in a string variable. var username = ""; Once users enter their name and click "Enter Site," they are directed ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

Effortlessly invalidate data within Next.js' app directory without utilizing fetch?

Evolution - Pre Next.js 13 Prior to the integration of the app directory in Next.js, developers could specify a revalidation parameter in the getStaticProps function: export async function getStaticProps() { return { props: {...}, revalidate: 10 ...

Ways to address the problem of returning assignments

I encountered an issue while working on my code Error message: Arrow function should not return assignment no-return-assign The problematic code snippet is as follows: await DB.Place.find( match, // key to filter (err, doc) => (listOfObje ...

Repositioning the chips/tags from inside to outside the Autocomplete box within MUI framework

I'm currently using the MUI Autocomplete component and I'm wondering if there is a way to move the chips/tags to be displayed outside of the input box. Ideally, I would like them to appear just below the input box so that the box can solely be us ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

The unique design of the list extends beyond the boundary line

In my current project, I am utilizing next.js and MUI (material-ui). The component I am working with has the following structure: <Paper> <List> .. </List> </Paper> One issue I am facing is that when the list is scrolled, the ...

Can Stripe Elements be used to integrate CAPTCHA on a website?

Our Next.js website currently utilizes Stripe Elements for a donation form, allowing users to make simple one-off payments as guests. Below is the implementation of the 'submit' method for the form: export const makeOneOffPayment = async ( ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause, import React, { useEffect, useState } from 'react'; import VideoCardComponent from './VideoCard'; import Grid from '@mui/material ...