PrimeReact and styled-component
Asked Answered
S

2

8

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;
    }
`;
Scanlan answered 18/9, 2017 at 10:48 Comment(0)
J
4

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;
    }
`;
Jeri answered 18/9, 2017 at 13:37 Comment(0)
D
1

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.

Director answered 7/9, 2018 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.