When props are used, the styles of styled components are overwritten

Here are some styled components that I have:

const Box1 = styled.div`
  // some styles
`;

const Box2 = styled.div`
  background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};

  ${Box1} > & {
    color: ${({ someProp }) => someProp ? "red" : "green"};
  }
`;

I am using these components in the following way:

<Box2 someProp>Box2 (bg: cyan, color: black)</Box2>
<Box2>Box2 (bg: magenta, color: black)</Box2>
<Box1>
  <Box2 someProp>Inner Box2 (bg: cyan, color: red)</Box2>
  <Box2>Inner Box2 (bg: magenta, color: green)</Box2>
</Box1>

The HTML output is as follows:

<div class="pages__Box2-doZfs hsqqBA">Box2 (bg: cyan, color: black)</div>
<div class="pages__Box2-doZfs iQIEMM">Box2 (bg: magenta, color: black)</div>
<div class="pages__Box1-ifSjDr">
  <div class="pages__Box2-doZfs hsqqBA">Inner Box2 (bg: cyan, color: red)</div>
  <div class="pages__Box2-doZfs iQIEMM">Inner Box2 (bg: magenta, color: green)</div>
</div>

The expected styles output should be:

<style>
  .hsqqBA {
    background-color: cyan;
  }

  .pages__Box1-ifSjDr > .hsqqBA {
    color: red;
  }

  .iQIEMM {
    background-color: magenta;
  }

  .pages__Box1-ifSjDr > .iQIEMM {
    color: green;
  }
</style>

However, the actual styles output that I am getting is:

<style>
  .hsqqBA {
    background-color: cyan;
  }

  .pages__Box1-ifSjDr > .pages__Box2-doZfs {
    color: red;
  }

  .iQIEMM {
    background-color: magenta;
  }

  .pages__Box1-ifSjDr > .pages__Box2-doZfs {
    color: green;
  }
</style>

This is causing the third instance of Box2 to have a color of green instead of red.

My question is why does this happen and how can I resolve it?

Thank you

Answer №1

After conducting some research online, I discovered that the key to successfully incorporating props into other components lies in using && instead of &.

const Box1 = styled.div`
  // add your styles here
`;

const Box2 = styled.div`
  background-color: ${({ someValue }) => someValue ? "skyblue" : "pink"};

  ${Box1} > && {
    color: ${({ someValue }) => someValue ? "yellow" : "purple"};
  }
`;

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

Retrieving an Object from an Object Group in javascript

I am encountering an issue while looping through something. https://i.sstatic.net/JkqcP.png However, I'm facing difficulties in obtaining the [["PromiseValue"]] object. If anyone can assist me with this, I would greatly appreciate it. Update : Th ...

Learn how to modify the condition in an 'if' template tag using JavaScript

I've been attempting to load a value obtained from clicking a button into an if statement within my HTML template, but have hit a roadblock. Perhaps I'm approaching this the wrong way. I tried utilizing the var tag and placing my variable inside ...

"Encountering an issue with Nextjs GraphQL mutation while trying to

Below is the code I use to remove a user: const [selected, setSelected] = useState<string | null>(null); const DELETE_USER = gql` mutation RemoveUser($_id: String!) { removeUser(_id: $_id) } `; const [removeUser, { loading, error }] = useMut ...

Attempting to extract JavaScript URLs using scraping methods, however, receiving an empty string when utilizing

I need help accessing and extracting data from a URL that is embedded within a specific tag. The tag in question looks like this: <script src="http://includes.mpt-static.com/data/7CE5047496" type="text/javascript" charset="utf-8"></script> S ...

Looking to add a dynamic divider between two columns that can be adjusted in width by moving the mouse left and right?

If you're looking for an example of two columns adjusting their width based on mouse movement, check out this page from W3Schools. I'm trying to implement this feature in my React app, but I'm unsure of how to proceed. Below is the JSX code ...

How can React.js render a random image while updating state?

I'm currently developing a fun game where country flags flash one by one on the screen, and the game stops on a particular flag after clicking a button. Here is a snippet of what I have created so far: import React from 'react' import ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

What is the purpose of adding this webkit CSS rule?

Whenever I open Chrome developer tools, I come across something that puzzles me. I always assumed that a CSS property is crossed out when it's overwritten by another class. However, I found myself in this peculiar situation: https://i.sstatic.net/Xm ...

The weight of the Blender model is excessive

Seeking advice on optimizing loading times for my threeJS website. Currently experiencing long initial loading due to 4 models and textures. Check it out: Any suggestions on how to effectively reduce model size would be greatly appreciated! Thank you in ...

Ways to position one div below another div

I need the #blue div positioned below the #green div The #blue div should have a margin-top: -10px; property <style> #red{ width: 400px; border: 1px solid red; } #green{ width: 100%; height: 100px; ...

Leveraging summernote in meteor with Discover Meteor tutorial

Recently, I've been delving into the world of Discover Meteor and encountering some challenges along the way. My current hurdle involves integrating content entered in summernote into mongo, but it seems to be more complicated than expected. The fil ...

Retrieving a specific document from an array that meets a specific query using MongoDB in JavaScript

I have a collection of data stored in MongoDB structured like this: users: { { user_id: 1000, activities: [ {id: 1, activity: 'swimming'}, {id: 2, activity: 'running'}, {id: 3, activi ...

When a div is created outside of the viewport, the overflow scroll feature will fail to function properly

I am currently working on developing a full screen slider with a unique feature on the last slide: a horizontal scrolling area. To achieve a smooth animation, I am using CSS translations to bring the div within the viewport. Oddly enough, the scrollbar do ...

What is the process of utilizing an npm package as a plain JavaScript library through require and module export?

Hey there, I'm a bit unsure if I'm on the right track with my question, but here it goes: What steps do I need to take to modify a node.js package for use as a standalone embedded script/library in HTML? How can I invoke a class constructor in ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

Protractor - Saving data for future utilization

Is it possible to retrieve a value once from one test and use it in another test later on with Protractor? In my particular situation, I am looking to extract a cookie from the browser just once and then make it accessible in all of the spec files used for ...

Navigating through Node's asynchronous behavior

I am currently developing a web scraper that gathers data about various shirts from a specific website. I have successfully set up all the necessary NPM packages in Node.js to scrape the information and save it to a CSV file. However, I have encountered ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...

Issue: Duplicate modules found in CKEditor 5 causing errors

Looking for assistance with integrating CKEditor 5 into a web application built with Vue.js and Laravel. To install the necessary dependencies, I used the following command: npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic as ...