Customizing PrimeReact Styles

I've been on a quest to find the perfect solution for customizing the default 'Nova' theme used in Prime React. While I know there is a theme designer available for purchase, I'd prefer not to go that route. In the past, I found myself cluttering my react application with a scss file for every tsx file, littered with !important tags like so -

.p-dropdown-trigger {
   background-color: brown !important;
   margin-left: 5px !important;
}

This led to a messy situation with excessive !important declarations scattered throughout. I contemplated commenting out the import for the Prime React theme in my index.tsx file

// import 'primereact/resources/themes/nova/theme.css';

And instead importing my own scss file..

import './styles/Override.scss';

However, this resulted in the styling disappearing completely and the page resembling plain HTML. I'm considering copying all the code from the Nova theme file and gradually tweaking it in the override file.

Does anyone have any better suggestions or ideas? Thanks

Answer №1

To streamline the process, you can consider duplicating all of the CSS code and then concealing their imports. This approach may require additional effort depending on the specifics of your project.

An alternative method would involve creating an override.scss file to selectively modify rules. Utilizing SCSS nesting can help keep things organized. To avoid the use of !important, it's advisable to target HTML elements more precisely. For example, if a CSS rule is defined as:

body header ul a { color: pink; }

you can create an overriding rule that is more specific:
body header ul li > a { color: blue; }

In cases where the rule you wish to overwrite contains !important, you will need to utilize !important in your new rule to enforce the change.

Answer №2

Perhaps with access to more code on codesandbox.io, I could offer greater assistance.

Have you explored modular CSS options like Styled-jsx or Styled-Components?

If you're considering styled-components, this resource on PrimeReact and styled-components may be useful: PrimeReact and styled-component

An alternative approach could involve linking the PrimeReact stylesheet before your own in the HTML. However, this solution would require a thorough analysis of the webpack's style implementation.

I hope this information proves helpful in some way :)

Answer №3

Subsequent CSS imports that follow the theme will take precedence over the templates because the final CSS rule holds greater specificity in CSS

In a create-react-app index.tsx (typescript .js) scenario, the index.css will override the initially imported prime themes, while CSS imports within the child React "App" component will not override the theme due to its prior import order. (Remember, the last relevant CSS rule applies unless overridden with !important.)

    import React from "react";
    import ReactDOM from "react-dom";
    import reportWebVitals from "./reportWebVitals";
    import App from "./App";
    
    import "../node_modules/primereact/resources/themes/saga-blue/theme.css";
    import "../node_modules/primereact/resources/primereact.min.css";
    import "../node_modules/primeicons/primeicons.css";
    
    import "./index.css";
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById("root")
    );

To ensure your React component's CSS (such as "App") takes precedence over React Prime theming, import the theme CSS first, followed by component-specific CSS imports to establish later and higher precedence.

    import "../node_modules/primereact/resources/themes/saga-blue/theme.css";
    import "../node_modules/primereact/resources/primereact.min.css";
    import "../node_modules/primeicons/primeicons.css";
    
    import React from "react";
    import ReactDOM from "react-dom";
    import reportWebVitals from "./reportWebVitals";
    import App from "./App";
    
    import "./index.css";
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById("root")
    );

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

The steps to display a partial view within another view in React Native

Attempting to show the View after calling alert("Hi") in the renderMoreView function has been challenging for me. The alert works fine, but displaying the View is where I am encountering issues. class Main extends Component { state = { moreButton: f ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

Issues with the execution of Jquery function

Hey guys, take a look at my code: //Additional Jquery codes // display_popup_crop : revealing the crop popup function display_popup_crop(link) { alert("show_popup_crop function is triggered!"); // changing the photo source $('#cropbox&a ...

How come ng-class doesn't apply to a specific class name?

I recently wrote the following code: <style> .dotted { border:dotted; } </style> .... <p ng-style="mystyle" ng-class="dotted">{{ answer }}</p> My intention was to have the paragraph element enclosed within a ...

Transforming an HTML document into a C# string representation

I need help creating a basic HTML file and then dynamically loading it as a string in C#. I attempted using File.Open, but the file is located separately from the binary code. Is there an easy way to instruct the build process to load it into a string? ...

What is the earliest React version compatible with @fluentui/react-northstar?

This specific project utilizes react version ^17.0.1 with fluentui/react-northstar. I encountered an error in the package.json file when attempting to run npm i @fluentui/react-northstar. Any insights into what might be causing this issue? Error message ...

Validating Forms with Jquery across Various Inputs

My HTML page includes multiple dynamically generated forms, ranging from 1 to 4 in number. I am looking for a way to validate each input field when the form is submitted. Below is the code I have: <script type="text/javascript"> $(document).re ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

How can you override the selected classes for menu items in Material-UI using React.js?

Hey there! I'm facing an issue where I can't override the class that displays the correct styling when a menuItem is selected. Below is my code: <MenuItem component={Link} to="/Acceuil" className={{root:classes.menuItem ,selected:cla ...

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

Custom palette in Material UI design palette allows users to create

Hey there everyone! I've been working on a website using ReactJS and Material UI, starting with this cool template. One thing I'm trying to do is change the color of the TextField when it's focused. Right now it's blue, but I want it ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

What is the best way to set a javascript variable as the props value for a component in React?

I decided to create a new component called CheckboxFilter. In order to utilize it and assign properties to it, I need to pass props with the value of a JavaScript variable : const FilterWrapper = ({ component, filterLabel, requiredField, ...others }) => ...

Image showcase with React

Apologies for what may seem like a simple question, but I am new to working with React and would appreciate some guidance. I am trying to create an image array gallery by pulling images from a folder within my project directory. However, despite multiple a ...

Encountering a CORS error in my Next.js 13.4 application while attempting to retrieve JSON data

Here is the location of the actual fetch request in our search/page. import { useSearchParams } from "next/navigation"; import Footer from "../components/Footers"; import Header from "../components/header"; import { format } ...

Retrieve the values and IDs for every span element within the form

I have been attempting to retrieve all span elements within a form and make them editable input text fields. Once you click away, they should revert back to span elements. I will provide a live example in the attached fiddle. I tried my hand at it, but the ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

Transmitted a file from React to Node but received an empty object

After retrieving image data, I am sending this data to the server and checking if it exists using console.log. const [fileData, setFileData] = useState(""); console.log("fileData:", fileData); const getFile = (e: any) => { setFileData(e.target.fi ...

`Property cannot be redefined: __internal__deprecationWarning` detected in a Shopify Hydrogen development project

Recently, while working on my Shopify Hydrogen project using Remix and Typescript, I encountered a sudden error when running npm run dev. Everything was functioning perfectly just 5 hours ago, but after returning from dinner, the app refuses to launch. ╭ ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...