Utilizing nested components with distinct styling techniques

I have a react component that accepts the size prop as either small, regular, or large. Depending on the size, a specific CSS class is assigned to style the component accordingly. Here's an example of how these classes are defined:

.my-component {
  &--small-size .column {
    height: 40px;
  }
  &--regular-size .column {
    height: 60px;
  }
  &--large-size .column {
    height: 80px;
  }
}

The issue arises when nesting these components (as shown below), where the nested component inherits the size of its parent instead of having independent styles - this appears to be a CSS limitation.

Is there a way to address this problem so that nested components always maintain their own unique styles?

const Page = (props) => {
  return (
    <MyComponent size="regular">
      {/* Other HTML elements*/}
      <MyComponent size="small">
        ...
      </MyComponent>
    </MyComponent>
  );
};

Answer №1

Rearrange the sequence in which the styles are included.

.my-component {
  &--small-size .column {
     height: 40px;
  }
  &--regular-size .column {
      height: 60px;
  }
  &--large-size .column {
      height: 80px;
  }  
}

In CSS, when items have the same specificity, the last item will override the previous ones. Therefore, since 'small' is nested within 'regular', your CSS should reflect this hierarchy as well.

Answer №2

If you prefer a manual approach using only css, you can structure it like this:

.my-component {
    &--small-size .column,
    &--regular-size &--small-size .column,
    &--large-size &--small-size .column {
      height: 40px;
    }

    &--regular-size .column,
    &--small-size &--regular-size .column,
    &--large-size &--regular-size .column
    {
      height: 60px;
    }

    &--large-size .column,
    &--small-size &--large-size .column,
    &--regular-size &--large-size .column
    {
      height: 80px;
    }
  }

Alternatively, you can use inline styles as a fallback option:

const small = {height : '40px'};
const regular = {height : '60px'};
const large = {height : '80px'};

const Page = (props) => {
    return (
      <MyComponent style={regular}>
        {/* Some other HTML elements*/}
        <MyComponent style={small}>
          ...
        </MyComponent>
      </MyComponent>
    );
  };

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

If you encounter the error message "The term 'Office' is not defined no-undef" it may be due to using a version of react-script that is newer than 3.0.0

I encountered an issue while creating an Outlook add-in using React and Typescript. When I tried to run my code with npm run start, I received the following error message, preventing me from running my React app. Failed to compile. ./src/index.tsx Line ...

Box surrounding the image with a shade of gray, all thanks to

Despite trying to set "outline: none" and tweaking the border, I'm unable to resolve the issue. For reference, you can visit the page here: . I've shared the link because I'm unsure of what exactly needs fixing or adding on the page. Any gui ...

Scaling Youtube video backgrounds with Squarespace

How can I inject a code into Squarespace to scale a video as the background and still keep the navigation functional? Here is the current code I am using: <div style="position: fixed; z-index: 50; width: 100%; height: 100%"> <iframe frameborder= ...

While trying to access localhost:3000/cart, an error occurred when attempting to connect to localhost:3000/api/products/cart resulting in a 404

I am currently developing an E-commerce platform and running into a problem while implementing the 'cart' route. The issue I encountered is shown in the following Error: Error image The localhost address for the cart is :3000/cart, but the error ...

Pass SASS/SCSS variables to Javascript without the need to export them to CSS files

Context Let's take a look at the _variables.scss file below: /* Setting up color variables */ $white: #fff; $black: #000; $grey: #ccc; // and so on... // Export the color palette for Javascript accessibility :export { white: $white; ...

How can I create a unique overlay popup for each item in an iterated list using Django template?

Generating an iterated list of titles from context received by the template in Django is simple: {% for instance in object_list %} <li>{{instance.international_title}} </li> {% endfor %} CSS makes it easy to create a popup overlay as well: # ...

Updating Credit Card Expiration Date live

As I work on splitting a credit card expiration date into two separate values within my formData, here is how the component is currently set up: const [ formData, setFormData ] = useState({ email: '', password: '', username: '&apos ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Utilizing React-virtualized: maximizing minWidth exclusively

Can anyone help me figure out how to make the last column width equal to all available space in a block? I've tried setting minWidth, but it's not quite working... Whenever I set a large width for the last column, my other columns on smaller scr ...

How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements. Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) b ...

Ensuring all fetch requests are completed successfully before dispatching an action in React-Redux

I'm currently developing a React application and utilizing Redux to manage the state. Here is a snippet of the code: category-arrows.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; i ...

Ways to hover and efficiently organize components?

My elements are floated with a width of 20%, resulting in 5 elements per line. The current arrangement looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Now, I want to reorganize them vertically as follows: 1 4 7 10 13 2 ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

When the React component's state is updated, an animation is triggered in a subcomponent connected to the parent component

The ProjectsSection component is responsible for rendering a document section with a header and cards. The goal is to trigger a header animation only when the header becomes visible on the screen for the first time and have it run once. However, adding a s ...

Implementing event emitters in a React and Node.js application to connect to a socket.io server through an

I am currently using socket.io to send messages to the client. While I know that I could achieve this by using the HTTP response from the express route, my intention is to emit messages as I receive data from an API in a real-world scenario. However, the ...

What methods are available to test my website across different browsers such as outdated versions of Internet Explorer like IE8?

Currently, I am working on Chrome with Windows 7 OS installed. However, Windows 7 does not support Internet Explorer 8. This is causing issues when trying to view my web pages in the IE8 version and older. How can I resolve this problem? I have attempted ...

Transitioning the height of a webpage element from a fixed value to fit the content dynamically

I'm trying to create a div that smoothly transitions from a set height to a height based on its text content. This likely involves considering the window width, as narrower windows cause text wrapping and increase the required height. #object { w ...

What causes the small black line to appear on the right side of an image when it is turned into a link?

When I turn an image into a link, why does it always seem to display a tiny black line to the right of the image? ...

What is the best way to change the className of an extended component?

I'm currently facing a challenge in positioning this component differently on a specific page. Despite providing it with another className property, it seems to only take on the original class's styling that was assigned during the component decl ...

Guide to verifying the displayed react component post a delay during testing

I am curious about how to effectively test the display of an interval dependent timer after a few ticks using React Testing Library and Jest. Consider the following code snippet: import React, { Component } from 'react'; let timer; class Test e ...