Custom components receive specific values through Styled Components

Hey there! I'm currently working on customizing the color of a button based on its type within a modal. The button can be categorized as either "Success" or "Danger":

import React from "react";
import styled from "styled-components";

const ButtonStyled = styled.button`
    background-color: ${(props) =>
        props.btnType === "Success" ? "green" : "red"};
    border: none;
    color: white;
    outline: none;
    cursor: pointer;
    font: Regular 400;
    padding: 0.5rem 0;
    margin: 0.5rem 1rem;
    font-weight: bold;
    margin-left: 0;
    padding-left: 0;
`;

const Button = (props) => {
    console.log(props.btnType);
    return (
        <ButtonStyled btnType={props.btnType} onClick={props.clicked}>
            {props.children}
        </ButtonStyled>
    );
};

export default Button;

Here's where the customized button is utilized:

import React from "react";
import Button from "../../UI/Button/Button";

const OrderSummary = (props) => {
    return (
        <div>
            <Button btnType="Danger" clicked={props.cancelPurchase}>
                Cancel
            </Button>
            <Button btnType="Success" clicked={props.continuePurchase}>
                Continue
            </Button>
        </div>
    );
};

export default OrderSummary;

This is where the Order Summary section is included:

import React, { useState } from "react";
import Modal from "../../components/UI/Modal/Modal";
import OrderSummary from "../../components/Burger/OrderSummary/OrderSummary";

const INGREDIENT_PRICES = {
    salad: 0.5,
    cheese: 0.4,
    meat: 1.3,
    bacon: 0.7,
};

const BurgerBuilder = () => {
    const [ingredients, setIngredients] = useState({
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0,
    });

    const [totalPrice, setTotalPrice] = useState(4);

    const [purchasing, setPurchasing] = useState(false);

    const purchaseCancelHandler = () => {
        setPurchasing(false);
    };

    const purchaseContinueHandler = () => {
        alert("continue");
    };

    return (
        <div>
            <Modal show={purchasing} modalClosed={purchaseCancelHandler}>
                <OrderSummary
                    continuePurchase={purchaseContinueHandler}
                    cancelPurchase={purchaseCancelHandler}
                    ingredients={ingredients}
                    price={totalPrice.toFixed(2)}
                />
            </Modal>
        </div>
    );
};

export default BurgerBuilder;

Finally, the following code snippet showcases the application of buttons within the modal:

import React from "react";
import styled from "styled-components";
import Backdrop from "../Backdrop/Backdrop";

const ModalWrapper = styled.div`
    box-shadow: 0 5px 16px rgba(0, 0, 0, 0.2);
    background: #fff;
    justify-content: center;
    align-items: center;
    color: #000;
    display: grid;
    grid-template-columns: 1fr 1fr;
    position: fixed;
    z-index: 500;
    border-radius: 10px;
    transition: all 0.3s ease-out;
    padding: 16px;
    left: 15%;
    top: 30%;

    @media (min-width: 600px) {
        width: 500px;
        left: calc(50% - 250px);
    }
`;

const ModalContent = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    line-height: 1.8;
    color: #141414;
    p {
        margin-bottom: 1rem;
    }
    button {
        padding: 10px 24px;
        background: #141414;
        // color: #fff;
        border: none;
    }
`;

const Modal = (props) => {
    return (
        <div>
            <Backdrop show={props.show} clicked={props.modalClosed} />
            <ModalWrapper
                style={{
                    transform: props.show ? "translateY(0)" : "translateY(-100vh)",
                    opacity: props.show ? "1" : "0",
                }}
            >
                <ModalContent>{props.children}</ModalContent>
            </ModalWrapper>
        </div>
        // <ModalStyled>{props.children}</ModalStyled>
    );
};

export default Modal;

During my testing, adjusting the button value in the Modal Content styled component directly influenced the color property of the Button Styled component. However, removing the button value caused an issue with accepting the color value in ButtonStyled. Any ideas why this might be happening?

Answer №1

The styling of the button in the ModalContent component is taking precedence over the button style defined in your Button component.

button {
    padding: 10px 24px;
    background: #141414; // <-- overrides button background color
    border: none;
}

In CSS, the most specific selector will dictate the style applied, and it seems that the ModalContent styled component has a more specific selector for button elements than the one from ButtonStyled.

To address this issue, you can increase the specificity of the background color in the ButtonStyled.

For more information on increasing specificity using pseudoelements and pseudoselectors, refer to the documentation here.

The ampersand can be used to boost the specificity of rules on the styled component, especially useful in scenarios where conflicting styles exist between styled components and vanilla CSS.

const ButtonStyled = styled.button`
  && {
    background-color: ${(props) =>
      props.btnType === "Success" ? "green" : "red"};
  }
  border: none;
  color: white;
  outline: none;
  cursor: pointer;
  font: Regular 400;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  font-weight: bold;
  margin-left: 0;
  padding-left: 0;
`;

Check out this CodeSandbox example for further reference.

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

How can I run global $PATH binaries as a no-home user using sudo?

When executing web-server-context-only operations, I run commands using sudo -u www-data {command}. Despite having NodeJS globally installed and in the root's path, it fails because the user www-data has a different path: /usr/local/bin. If I create a ...

Spring Security does not generate an error if the authorization header is missing following a login using AngularJS

Working on implementing HTTP Basic Authentication using Spring Security and Angular JS by including the Authorization header in $http headers: const headers = { authorization: "Basic " + btoa(this.login + ":" + this.password) }; this._$http.get("user ...

Calculating the mean value of an array containing objects with a single key-value pair in JavaScript

I have a list of users along with their ages, and I need to calculate the average age of all users. I initially attempted to use the reduce method for this task, but encountered syntax errors preventing successful implementation. Below is the code snippet ...

What is the best way to choose an item from a list nested inside a div?

Currently, I am facing the challenge of selecting an item from a list that is structured using a div For this task, I am utilizing WebDriver IO () <div class="selectize-dropdown demo-default select-class single" style="display: none; width: 196px; top ...

Is optgroup malfunctioning in IE 10?

My main question is: does optgroup not function properly in IE? The Plnkr code works fine in Chrome but encounters issues in IE 10. I'm trying to find a solution that will work across both browsers. Is this a known problem? In Chrome, I can expand/co ...

Encountering problem while exhibiting server's response message within a modal popup in Angular 6

I have implemented two custom dialog modals in an Angular component. The objective is to open the appropriate modal and display the response message. The component receives two values as Observables from my services: The name of the modal that needs to ...

Resolving a Tricky Challenge with jQuery's

I am facing an issue with a function that animates images through crossfading. This function is responsible for rotating banners on a website. By calling the function as animateSlideshow("play"), it starts animating and sets up a timeout. On the other hand ...

Is it possible to utilize a single MobX store across two distinct components within a React Native application?

I am working on a module that includes a topTabNavigator wrapped with mobx provider using the store: export class ModuleTeam extends Component { render() { return ( <Provider store={store}> <TopTabNavigator /> </Pr ...

Sending JavaScript Variables to MySQL Database via PHP

I'm currently attempting to pass a JavaScript variable to PHP, but I'm unsure of the best method to do this. I've heard about Ajax, but I haven't used it before and find it difficult to understand. Can anyone suggest an easier way to ac ...

I am puzzled by the behavior of a specialized React Native hook that causes the component using it to render twice in a row

Currently, I am diving into the world of custom Hooks in React-Native while utilizing AWS Amplify for my backend. In this process, I have come across the Auth.currentUserInfo method provided by AWS Amplify to fetch authenticated user information. The chall ...

The footer and login form are tangled up in a web of confusion

Here is my HTML code for a login form: <div class="middle-box text-center loginscreen"> <div> <form class="" role="form" action="index.html"> <div class="form-group&q ...

The constructor THREE.Geometry does not exist in this context

I have been working on a three.js open world game and I am trying to implement a rain effect. I have followed tutorials and looked through source code on various github repositories, but I still can't figure out what I am missing. Currently, I am usi ...

Issues with arrays and objects not functioning properly in local storage

Currently, I am working on implementing a TODO list that utilizes local storage to store data. Unfortunately, I have encountered an issue in my code that I am struggling to fix. In the getTaskArray() function, I retrieve an array from local storage using ...

Using Express for Managing Subdomains, Redirects, and Hosting Static Files

I am struggling to configure Express in a specific way and can't seem to get it right. Despite researching on various platforms like SO, I still can't figure it out. Hopefully, by explaining my intentions here, someone can guide me in the right d ...

ZeroMQ and Electron integration: Unable to find the specified bindings file

Currently, I am running Windows 7 x64 with nodejs 5.1.0 and Electron 0.35. I carefully followed the instructions provided by the Electron Quick Start app and then proceeded to add the line require("zmq") to the main.js file. However, upon executing npm ins ...

The JavaScript onClick function is unable to identify the object

"Newbie" JavaScript Question:-) I'm struggling with a JS function in my code: <script type="text/javascript"> $(function () { $('.shoppinglist-item-add').ShoppinglistItemAdd(); }); </script> This "shoppinglistI ...

What is the best way to include multiple stylesheets in ctx.renderPage?

I am facing an issue in my project where I want to use both Material UI and styled-components. Individually, they work fine, but when I try to integrate both, it seems to cause a problem. In my _document.ts file, I have set up Material UI like this: c ...

Exploring each list item within the specified unordered list

Here is a basic code snippet: var ulreq = $("#abc").children("ul.ghi"); var lists = ulreq.find("li"); for( var i = 0; i < lists.length; ++i){ alert(lists[i].text()); // Display the values in these li }<script src="https://ajax.googleapis.com/ajax ...

Ready to Opt-Out in RxJS 6?

My test is functioning properly at the moment, but changing the active value causes it to break. Therefore, I am looking to unsubscribe a (which is the current active Observable) before proceeding with any other tests: let a:Observable<Todo> = store ...

Show the array's selected value in a Vuetify select input

I am working with a dataset containing city names and corresponding values. The goal is to display the value when a city is selected. I know that {{selected.value}} will give me the selected value, but I need to manipulate this value for calculations such ...