How to override prime-react component CSS styling?

4.8k views Asked by At

I am using prime-react to style my React page. But I want a more compact website with very few padding and minimum styling. For this purpose, I want to override a few CSS properties for the prime-react components.

For eg, I am trying to reduce the padding for the MenuBar -

HomePage.js

import {React, Component } from 'react';
import { Menubar } from 'primereact/menubar';
import 'primereact/resources/themes/saga-blue/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import styled from "styled-components";

export default class HomeMenuBar extends Component {
    // menu code ...

    render() {
        return (
            <div>
                <div className="card">
                    <Menubar model={this.items} className={this.props.className} />
                </div>
            </div>
        );
    }
}

const ComponentView = styled(HomeMenuBar)`
    .p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link {
        padding: 0.1rem 1rem !important;
    }
`;

The above code makes no difference to the original styling. I am trying to make use of this component.

However, particularly using these styled-components I don't like it. I am new to react and would like to know if there are better alternatives like, storing the CSS properties in another file and then importing it in the required file. I tried this part but it also didn't work out.

2

There are 2 answers

3
Andrew Tvorch On BEST ANSWER

I work with react over a year and have seen lot of different ways to customise components and so far, I think that styled-components is the most convenient way to customize components if you cook them right. I love to put all customized components with styled to a separate file near the index.js called styled.js of Component.js and Componnet.styled.js (in the separate folder of course MyComponent/index.js);

In styled.js you export all components like this:

export const Container = styled.div`
    .p-menubar .p-menubar-root-list > .p-menuitem > .p-menuitem-link {
        padding: 0.1rem 1rem !important;
    }
`

In index.js file you inport them like this:

import {Container} from './styled' 
// or import * as Styled from './styled' (if you have a lot of customized components);

export default class HomeMenuBar extends Component {
    // menu code ...

    render() {
        return (
            <Container>
                <div className="card">
                    <Menubar model={this.items} className={this.props.className} />
                </div>
            </Container>
        );
    }
}

If you want to try something more like classic css try to look at css-modules. This article can help https://www.triplet.fi/blog/practical-guide-to-react-and-css-modules/

0
hakobpogh On

You can also try patch-styles, a more declarative way to apply CSS/SCSS modules to your code. Also, check out the StackBlitz example.