PrimeReact and styled-component

7k views Asked by At

I can't seem to style a PrimeReact component with styled-component.

Given the below code to render an InputText, my intention is to change the width of it. But it doesn't work.

import styled from "styled-components";
import {InputText} from 'primereact/components/inputtext/InputText';

class Component extends React.Component {
    render() {
        return (
            <InputText/>
        )
}

const ComponentView = styled(Component)`
    .ui-inputtext {
        width: 1000px;
    }
`;
2

There are 2 answers

0
Diego Haz On BEST ANSWER

styled-components generates a className that should be passed to the component.

import styled from "styled-components";
import {InputText} from 'primereact/components/inputtext/InputText';

class Component extends React.Component {
    render() {
        return (
            <InputText className={this.props.className} /> <---- here
        )
}

const ComponentView = styled(Component)`
    .ui-inputtext {
        width: 1000px;
    }
`;

If InputText doesn't accept className, you can simply wrap it with another component:

import styled from "styled-components";
import {InputText} from 'primereact/components/inputtext/InputText';

class Component extends React.Component {
    render() {
        return (
            <div className={this.props.className}> <---- here
                <InputText />
            </div>
        )
}

const ComponentView = styled(Component)`
    .ui-inputtext {
        width: 1000px;
    }
`;
0
Han Lazarus On

PrimeReact has a lot of styles applied with a separate sass stylesheet, often combining multiple classnames and html tags.

To get your styles to win, you need more CSS specificity.

A solution is to use a nested selector, like:

const ComponentView = styled(Component)`
&&& {
    width: 1000px;
}`

This will generate 3 identical classnames and is recommended by the Styled Components docs. More classname specificity needed? Use more &s.

Or you could put in a !important. I've seen this around.

Or edit their sass file.