Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the component along with the page-specific resources. However, this resulted in the following error:

Expected a template literal or String literal as the child of the JSX Style tag (eg: <style jsx>{`some css`}</style>), but got MemberExpression

I have two functional renders located in separate directories and files - one for a page and the other for a component:

src/pages/mypage/
    index.js
    styles.css
    myComponentStyles.css
src/components/MyComponent
    index.js
    styles.css

Including that file/directory referencing is not the issue here, below is the code snippet:

src/pages/mypage/index.js

import MyComponent from '../../components/MyComponent'
import styles from './styles.css'
import MyComponentStyles from './myComponentSyles'

const MyPage = () => {
  return (
    <div className="my-page-container">
      <style jsx>{styles}</style>
      <MyComponent styles={MyComponentStyles} />
    </div>
  )
}

export default MyPage

src/components/MyComponent/index.js

import styles from './styles.css'

const myComponent = props => {
  return (
    <>
      <style jsx>{styles}</style>
      <style jsx>{props.styles}</style>
      <div className="my-component-main-container">MyComponent</div>
    </>
  )
}

export default MyComponent

I am looking for a way to allow MyComponent to receive a stylesheet generated by another component. Any suggestions on how to achieve this?

Answer №1

Even though it may not provide a direct solution to the issue at hand, Styled JSX offers a unique feature in the form of the :global() pseudo selector. This allows you to style a component that exists outside the current component's scope. Take a look at this practical example:

src/pages/mycustompage/styles.css

.my-custom-page-container :global(.my-external-component){
  background-color: black;
}

The Next.js documentation provides insights on how to use the :global() pseudo selector:

A Special Case for Global Selectors

Sometimes, it becomes necessary to bypass selector scoping. To cater to this need, Styled JSX introduces the :global() selector, taking inspiration from css-modules.

This feature comes in handy when creating a global class that can be applied to third-party components. For instance, if you wish to style react-select and pass a custom class through optionClassName:

import Select from 'react-select'

export default () => (
  <div>
    <Select optionClassName="react-select" />
    <style jsx>{`
      /* The "div" element will be prefixed, but ".react-select" won't */

      div :global(.react-select) {
        font-size: 16px;
      }
    `}</style>
  </div> )

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

"Access denied" error when using Internet Explorer and jQuery

Attempting to make an AJAX call using jQuery's $.post in Internet Explorer is resulting in an error message stating "Permission denied." This peculiar issue only seems to occur when accessing a page after having visited another page. For example, if ...

Is the webdriver.io waituntil method designed to return a boolean value of true or false

I am working on an automation framework using webdriver.io v5. I need to receive a boolean response from the code snippet below: waitAndCheckForContactToBePresent(contactName) { return browser.waitUntil((value) => { return this.chec ...

Toggle the visibility of a dropdown menu based on the checkbox being checked or unchecked

One challenge I am facing involves displaying and hiding DropDown/Select fields based on the state of a Checkbox. When the checkbox is checked, the Dropdown should be visible, and when unchecked, it should hide. Below is the code snippet for this component ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

What is the best way to ensure that the size of a header is balanced on both margins?

I just recently began learning CSS about a week and a half ago, and I'm facing a challenge that I'm struggling to overcome. I want my webpage to have the same design as shown in this image, but despite trying various solutions, I can't seem ...

Implementing custom CSS styles to a component in real-time with ng-style

When I use an angularjs component to create stylized pictures, the style is not applied correctly on the first visit to a page (refreshing the page shows the correct style). The CSS that should be applied is generated dynamically based on the height and wi ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Divide a JavaScript project into multiple packages using either webpack or npm

I am embarking on the development of an application that needs to be compatible with Windows (PC), Android, and iOS. To achieve this, I plan to use Electron for Windows and React Native for mobile platforms. Both applications will be built using React and ...

What is the reason behind the warning about DOM element appearing when custom props are passed to a styled element in MUI?

Working on a project using mui v5 in React with Typescript. I am currently trying to style a div element but keep encountering this error message in the console: "Warning: React does not recognize the openFilterDrawer prop on a DOM element. If you in ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...

Translating Python's slicing assignment syntax to JavaScript/TypeScript: A guide

Currently, I am in the process of converting a Python library into TypeScript. One specific challenge I am facing is translating this line of code from this particular repository: is_prime[start - segment_min::pk] = repeat(False, len(range(start - segment ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Struggling with incorporating GlobalStyles in the app.tsx file

I have been working with next13 and styled-components. Initially, everything seemed fine in my file globalStyles.ts, and all was functioning perfectly. However, I started encountering errors related to the import of <GlobalStyles/>. Specifically, th ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Transferring multiple sets of data from Firestore to another collection proves to be ineffective

Currently, I have four separate collections stored in my firestore database: EnglishQuestions MathQuestions ScienceQuestions DzongkhaQuestions My goal is to consolidate all the data from these individual collections and organize it under one collection f ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

The `overflow:auto` property is causing the flex container to overflow due to the size of its fixed width children

Here's a unique CSS puzzle for you all: Imagine the following hierarchy: app container flex container item1 - fixed width(80px) item2 - responsive width(width:100%). MUI Stepper - overflow:scroll, width:100% This structure would look like this: ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...