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

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Why is my database being accessed by my Prisma unit tests?

After following the Unit testing with Prisma guide, I wrote a unit test for a function that interacts with my database. Despite mocking the Prisma client as suggested in the guide to prevent database calls, when I run the test, data is actually created in ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

Using JavaScript to execute a JSON parse function will not work

I am currently working on this code and would appreciate any assistance. I'm trying to retrieve and parse data from my listApp.json file to display a list with one link. As a beginner, I could use some guidance. <script type = "text/javascript"> ...

Issue with next-intl plugin when choosing enum-based values is not functioning correctly

For my next.js project (version 13.4), I was in need of next-intl translation support. I followed the official example provided at The example mentioned to define the following code in the 'en.json' file: "message": "{gender, sele ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

The functionality for inserting data via Ajax in WordPress is failing

Greetings, I am currently in the process of developing a popup plugin for WordPress that involves inserting data into a database using AJAX. Everything in my code is functioning correctly up until the jQuery section, where the data fails to insert into the ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

When viewed on mobile devices, the image shrinks significantly

I'm experiencing an issue where the image shrinks significantly when viewed on a mobile device or when zooming in the browser. Can you help me understand why this is happening and suggest a solution? Here are the HTML and CSS code snippets: HTML < ...

In my Cypress test for a new Next.js 13 app directory, I am looking to mock the session object for the api/auth/session route in NextAuth. Can you provide guidance

I have recently upgraded to the latest version of Next.js, which is 13, and I am now utilizing next-auth for authentication. The challenge I am facing is that the session is generated server-side, making it inaccessible in Cypress testing. My goal is to mo ...

Creating a Dynamic Login Panel Using HTML, CSS, and Jquery

Designing a dynamic sliding login panel utilizing Html, CSS, and jquery alongside various plugins. Check it out here: http://24.125.42.135/ When activated, the bar smoothly pushes down the content (click on the login option at the top right corner). This ...

Dealing with an unexpected token error in JSON? Learn how to properly handle removing special characters like quotation marks and line breaks to

After receiving a JSON response from the server during page load, I successfully populate it on the page using Handlebars.js. However, I am facing difficulties in storing this JSON object in a JavaScript object. Here is what I tried: var jsObject = "{{o ...

Adjust font size on specific breakpoint in React using Ant Design library

Is there a way to adjust the font size based on the breakpoint in Antd React? <Text type={"secondary"} style={{fontSize: '36px'}}>Message for {userName}</Text> ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...

I'm curious if it's possible to utilize Raspberry Pi GPIO pins within a JavaScript frontend

Is it possible to utilize Raspberry Pi's GPIO pins in Javascript? Specifically, I am interested in reading the values of the Raspberry Pi PIR sensor without having separate Python and Javascript applications. Ideally, I would like a solution that inte ...

Navigating through the website has become quite challenging due to the malfunctioning navigation bar. Instead

I recently completed a website and designed an awesome navigation bar in a separate file. However, when I combined them together, the navigation bar disappeared. The background of my "list" div should be filled in and larger, but it's not working as e ...

Complete alignment of several elements in a horizontal scrolling container

In the table-like container, I have elements with horizontal scrolling. Each element has the same width but potentially different heights. I want to add a button in the top-right corner of each element without it disappearing when scrolling. I came across ...

Unlocking the secret path to reach an untraceable object nested within another object using

After using php's json_encode() function, I received a string that looks like this: [ { "key1":"value1", "key2":"value2", "key3":"value3" }, { "key1":"value1", "key2":"value2", "key3":"value3" } ] To convert the string into a J ...