Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve this, I attempted removing node modules, installing npm react-scripts, and then running npm install again. However, now when I execute the command 'npm start', I am presented with the following error:

ERROR in ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/App.scss)
Module build failed (from ./node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js):
SassError: Top-level selectors may not contain the parent selector "&".
   ╷
10 │     &::-webkit-input-placeholder {
   │     ^
   ╵
  src\scss\_mixins.scss 10:2            placeholder-color()
  src\scss\basic\_typography.scss 59:1  @import
  src\scss\_style.scss 7:9              @import
  src\App.scss 1:9                      root stylesheet

Furthermore, here is the snippet from my package.json file:

{
  "name": "tf-react",
  "version": "4.6.0",
  "license": "MIT",
  // Dependencies listed...
}

Answer №1

I recently encountered a specific error in my project related to mixins, and I have a thorough understanding of the cause of the error, why it occurs, and how to resolve it.

The error stems from the presence of the & character in the mixin, which serves as a placeholder for the "parent selector" in SCSS – referring to the selectors that come before the current block within the curly braces.

For instance, in the example below, the parent selector is main input:

main {
    input {
        @include placeholder-color(red);
    }
}

This results in the following CSS rule:

main input::-webkit-input-placeholder {
    color: red;
}

If the mixin is called without any surrounding selector blocks like this:

@include placeholder-color(red);

SASS will try to generate the following erroneous CSS rule:

<parent selector>::-webkit-input-placeholder {
    color: red;
}

This leads to an error message stating that top-level selectors cannot contain the parent selector.

To address this issue, I crafted a solution using a Sass code snippet with an @if clause to handle cases where the & is null.

Here's a general example of how you can implement this fix:

@mixin placeholder-color ($color) {
  $s: #{if(&, '&', '')};

  #{$s}::-webkit-input-placeholder {
    color: $color;
  }
}

In this code snippet, note the usage of the new placeholder variable $s, the logic enclosed within #{}, and the interpolation #{$s} for including the placeholder in the selector.

Although this resolution may not be relevant to your current situation, future users, myself included, can benefit from implementing this fix moving forward.

References for further reading:

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

When is the best time to invoke mapDispatchProps in Redux?

In my application, I have a parent component called ProfileScreen. This main component is made up of smaller child components such as ProfilePhoto and ProfileInfo. These child components allow me to edit information about the user, including their profile ...

How to change a date object into a datestring using the TZ format in JavaScript

Here is the input: const date = "06/01/2018" const time = "06:25:00" The desired output format is a string like this: "2018-06-01T00:55:00.000Z". I attempted to create the Date object using const result = new Date(date + time); //outputs an obje ...

How to dynamically assign a name attribute to tags in a string using React and JavaScript

Streamlining the current blog post. If I have a string let someText = "<h1>test</h1><p>desc of test</p>" I want to use React or JavaScript to transform it into someText = "<h1 id="test">test</h1><p>desc of test ...

Last item in Material UI Grid container not filling up entire space

I designed a Grid container with 2 Grid columns, each containing 3 elements. However, I am facing an issue where the last element of each column is not appearing at the bottom as intended. What could be causing this problem? For reference, you can view th ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

What could be causing the lack of data transfer between the server and client through socket.io within my express application?

My application in Node.js sends an object, gathered from a form on the client side, to Salesforce through their API. After receiving a success or error message, I want to relay it back to the client and display it. While Socket.io appeared to be the approp ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

The API Key containing a colon is causing a TypeError when trying to parse it because forEach is not recognized as a function

Trying to utilize the New York Times API to fetch the Top Stories in JSON, I am encountering an issue: Uncaught TypeError: top.forEach is not a function Suspecting that the problem lies with the API key containing colons in the URL, I attempted encoding ...

Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it. The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack ...

Choose all div elements except for those contained within a certain div

Having trouble with an IE7 z-index fixer that's affecting specific elements. I'm attempting to select all divs, excluding those nested within a particular div. Below is the jQuery code I'm using, but it's not functioning correctly: & ...

Sending table data with files or input string data to the server in .NET ASPX web forms is not allowed

When the add button is clicked, the product type, name, and file are added to the table. The variables are declared globally. document.getElementById("addBtn").addEventListener("click", function () { var entryExists = false; var documentName = doc ...

What steps need to be taken to utilize the fast-json package within a web browser environment?

In my quest to enhance the performance of my apps, I stumbled upon two intriguing packages. Currently, I am working on a forum-style app that constantly receives and processes information from APIs. Despite optimizing my frontend JavaScript to the best of ...

Preventing browser flickering when using 'loadURL' to switch between URLs in Electron

Within my electron app, I am utilizing a singular window. As users navigate through the various "forms" within the application, I make use of the mainWindow.loadURL('file://...') function. Unfortunately, this approach leads to a flashing effect w ...

several ngGrids and ngGridEventScroll

There are 2 separate ng grids on a single page, each with infinite scrolling that loads server-side data on ngGridEventScroll. scope.$on('ngGridEventScroll', function(event) { ... }); Each grid is designed to make its own unique server-side cal ...

As soon as my fingers grace the keyboard, the website springs to life before my

My Node/Express application is displaying some unexpected behavior that I'm struggling to understand. When I start typing the URL, the webpage instantly loads, all logs are populated, and I see my home screen. Currently working on local instance for b ...

Filtering HTML tables to display only one instance of each value

I have a 300x11(rowXcolumn) html table that I wanted to filter like Excel or Google Sheets's filter. Upon researching, I came across the code below on a website. While it works as desired, there is an issue where it displays the same value multiple ti ...

Bootstrap's hidden navigation bar feature

I noticed that my navbar changes from transparent to opaque when scrolling. I am trying to achieve a similar effect like the one in this example: Initially, my navbar looks like this: As you can see, it has a light border and the font is not white. Howev ...

I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble. I faced an issue when I created a new component in the directory and placed my Button component there. Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define th ...

How come the 'color' property in the material-ui TextField functions properly, while the 'borderColor' property does not work as expected?

I am trying to show a TextField in orange color: <TextField id={field_meta.name} label={field_meta.title} defaultValue={field_meta.value? field_meta.value: ""} onChange={this.handleChange} margin="normal" inputProps={{style: {bo ...

ngClass causing styling issue when applying styles

When I use class names like error and info, the CSS works fine. For example, in this Angular app (latest version) here: https://stackblitz.com/edit/github-i4uqtt-zrz3jb. However, when I try to rename the CSS classes and add more styles, like in the examp ...