A guide to declaring a SCSS attribute selector with a <length> type using a REACT property

I am looking to develop a versatile component in React that can be customized externally:

AnotherPlace.tsx

...
<BarComponent width={200}>
...

BarComponent.tsx

interface IBarProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IBarState{
  checked: boolean;
}

class BarComponent extends Component<IBarProps, IBarState> {
    constructor(props: IBarProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (
          <div className="bar-component"
              data-width={this.props.width + 'px'}
          >
          ...

BarComponent.scss

.bar-component {
    ...
    width: attr(data-width length);
    ...

However, I keep encountering an error when running the application (chrome):

https://i.sstatic.net/oenLm.png

... It is essential for me to have a "number" as a property due to calculations needed for inner components so that everything functions seamlessly together.

EDIT:

Using "style" has not been effective for me as it interferes with the ::before ::after features in my scss which rely on modifying "right:" based on the width.

For a clearer picture, this is the foundation of my project: https://www.sitepoint.com/react-toggle-switch-reusable-component/

Answer №1

In response to your query

Kindly provide a solution using attribute selector or inform me of its impossibility due to X reasons (include link to documentation if possible).

Regrettably, despite its potential usefulness, current research suggests that it is not currently feasible:

MDN on CSS attr():

Note: While the attr() function can be applied to any CSS property, support for properties other than content is considered experimental, and backing for the type-or-unit parameter is limited.

According to information from caniuse.com concerning css3-attr, the capability to utilize attr() with any CSS property (excluding content), and for non-string values (such as numbers, colors) via <type_or_unit> as per "CSS Values and Units Level 3", is currently not supported by browsers.

Please also refer to the statement in the ongoing draft for "CSS Values and Units Module Level 4":

The following features are considered at risk and may be eliminated during the CR period: toggle(), attr() [...]

(Source: https://drafts.csswg.org/css-values/#status)

A Chromium issue led me to an intriguing resource I wasn't previously aware of: web-platform-tests dashboard for css-values. Explore the (failing) tests prefixed with attr-, especially attr-length-valid.html and attr-px-valid.html.

However, there is optimism: the Chromium team recently (05/15/2020) proposed an Intent to Implement and Ship: CSS advanced attr() function

To incorporate the augmentation to attr() outlined in CSS Level 4, specifically permitting various types (besides ) and usage across all CSS properties (apart from pseudo-element 'content').

Note: CSS Level 4 has significantly revised attr() compared to Level 3 to simplify implementation. We will adhere to CSS4. [...]

Motivation: This feature has been extensively requested, with 77 stars at crbug.com/246571. [...]

Chromium tracking Issue 246571: Implement CSS3 attribute / attr references )

Firefox also demonstrates recent activity, see Firefox tracking Bug 435426 [meta] Implement CSS Values 3 extensions to attr(), where they make reference to Chromium's ongoing efforts at least.

(WebKit Bug 26609 - Support CSS3 attr() function shows no activity, which could pose a challenge)

Answer №2

Following the advice of G-Cyrillus, I have managed to discover a potential solution utilizing CSS custom properties. Unfortunately, my search for a resolution using attribute selectors did not yield any results, so I had to stick to one type of solution.

To add your custom properties in the SCSS file within the "parent" class, do the following:

.foo-component {
    --customwidth: 150px;
    --custommargin: 5px;

    width: var(--customwidth, 150px);
    ...
    &-inner {
        margin-left: var(--custommargin, 5px);
    }
    ...
}

Once you have declared the custom property, you can use it with

var(<propertyname>, <initialvalue>)
.

When working with React, you can make slight modifications to the render() function like this:

 render(): ReactElement {
    // Set the custom properties for width, margin, and slider position
    let cssProperties = {};
    cssProperties['--customwidth'] = this.props.width == null ? '150px' : this.props.width + 'px';
    cssProperties['--custommargin'] = this.props.margin == null ? '150px' : this.props.margin + 'px';
    cssProperties['--switchposition'] = (this.props.width == null ? 115 : this.props.width - 35) + 'px';

    return (
      <div className="foo-component" style={cssProperties}>
      ...
}

This approach will work effectively for each component individually.

Answer №3

One simpler method is to utilize inline styling:

       return (
          <div className="bar-component"
              style=`height:${this.props.height};`
          >

Answer №4

When using the attr function in CSS, you must specify the attribute by selecting it within your SCSS styles.

.bar-element[data-height] {
    ...
    height: attr(data-height length);
    ...

If you have multiple attributes to style, you can target them like this:

.bar-element[data-height][data-padding] {
    ...
    height: attr(data-height length);
    padding: attr(data-padding number);
    ...

For more information, refer to the MDN documentation.

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

Ways to obtain the index of a button

Once upon a time, I used to create a plethora of buttons using a for loop. The title[] array was filled with numerous values. export const renderButtons1 = (numOfBtns,title,navigate) => { const views1 = []; for ( var i = 0; i < numOfBtns; ...

A step-by-step guide on leveraging the useRef hook to switch between different images

If I have an image gallery where users can click on an image and have it displayed in a larger format below the gallery, how can I utilize the useRef hook to switch the displayed image with the selected one upon clicking? Each image in the gallery will be ...

Traversing an object with a single identifier

Just starting out with React and attempting to iterate through some data. I have an array of objects where each object only contains a single property, which is another array. How can I access the keys "coins" and "bills" while looping through this informa ...

Enhancing Pixi.js functionality with TypeScript: Utilizing 'none' Module Settings

My project is a 100% JavaScript application that operates in the browser, consisting of around 20 JS files with all function names in the global scope. Whenever I make changes to a JS file, I can simply refresh the page and see the updates immediately. Ho ...

Verify Angular Reactive Form by clicking the button

Currently, I have a form set up using the FormBuilder to create it. However, my main concern is ensuring that validation only occurs upon clicking the button. Here is an excerpt of the HTML code: <input id="user-name" name="userName" ...

I am interested in incorporating various forms within this code

I followed an online tutorial to create this code, and I've made some edits myself, mainly related to the buttons that display information. However, I'm still learning and struggling with adding different forms to each section. I would really app ...

Troubleshooting non-responsive Bootstrap navigation bars in HTML/CSS

As I implement a Bootstrap Navigation Bar at the top of my webpage, I notice that it tends to collapse when the page hits a certain length. This seems to be a common feature among many Bootstrap Navbars, where all headings are condensed into a button on th ...

What is the correct way to write SVG markup within SVG tags in a React and NextJS environment?

I currently have a Svg component set up like this interface SvgIconProps { children: React.ReactNode; strokeWidth?: number; width?: number; height?: number; className?: string; } export const SvgIcon = ({ children, strokeWidth = 1, width = ...

Eliminate the gap between spans when wrapping words

I am facing a challenge with displaying text and an icon together in a div. The requirement is for the icon to always be positioned right next to the text, even when the text wraps due to limited space. Various solutions have been attempted, but they all ...

Having trouble adding animation to button element following the application of :after pseudo-element styling

I've been grappling with pseudo elements, but I just can't seem to make a simple button animation work using them. My goal is to have a panel move from bottom to top on hover. Similar to the button found on this page (1st row, 2nd button). From ...

How to center a container in HTML using Bootstrap techniques

Here is the code I have been working on: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/> <div class="span4 offset4 centered"> <div class="container overflow-hidden"> < ...

Adjust the dimensions of the initial cell

I need to adjust the size of the initial "generated" cell in a grid. The grid is not present in the HTML markup until JavaScript prints RSS information on it, making it difficult to target specific rows or cells directly. Note: The first element is hidden ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...

Using custom or external fonts icons in Chrome Packaged Apps involves the following steps:

Seeking to enhance the appearance of my Chrome Packaged App built in AngularDart, I searched for external icons online but came up empty-handed. Despite attempting various strategies and implementing the workaround provided below, I have been unable to ach ...

Trouble connecting socket.io to backend due to a 404 error

I am currently facing an issue while trying to establish a connection between my backend (localhost:5001) and front end (localhost:5173). Unfortunately, I keep encountering error 404 which states that the connection cannot be established. Below are the sn ...

Combining numerous inputs into an array in a React component

As a beginner in coding, I am eager to learn React by building a project. Currently, I am facing a challenge and seeking guidance. https://i.sstatic.net/Ic2zC.png My goal is to store all these values in an array structured as follows: { option: { s ...

Displaying jQuery Slide Elements in a row instead of stacking them on top of each other

I created a tutorial box with 4 slides (2 for this (demo)). My goal is to make the slides slide from right to left when the user clicks next. I have been able to achieve this, however, the elements are displaying on top of each other instead of side by si ...

Refresh the webpage in IE8 by utilizing compatibility view to ensure optimal performance

I have encountered an issue with a simple JavaScript method that opens colorbox on button click. The code works perfectly in all browsers except for IE8, where it refreshes the page and pushes the browser into compatibility mode. Here is a snippet of my co ...

Yelp API call resulting in an 'undefined' response

When attempting to make an API call using the yelp-fusion, I noticed that the logged result is showing as undefined. It seems like this issue might be related to promises or async functions. It's important for me to maintain this within a function sin ...

Acquire the stripe color scheme of Bootstrap tables

I have a Razor component that populates a series of divs within a container. Is there a way to utilize the table-striped color scheme for my odd divs without replacing it entirely? Alternatively, if I create a new CSS class called "Div-Stripe-Row." Can ...