in43sh
in43sh

Reputation: 943

Is it possible to assign CSS class to a React component?

Is it possible to assign CSS classes directly to a React component? The reason is that I have all the CSS responsible for Products in SCSS file responsible for products, but margins I want to have in Store component and assign it directly to Products and all other components there. I'm using create-react-app configuration. Code:

import React from 'react';
import Products from "./Products";

function Store() {
    return (
        <div>
            <Products className="store__products"/>
        </div>
    )
}

export default Store;

Upvotes: 0

Views: 1259

Answers (2)

in43sh
in43sh

Reputation: 943

I did it as suggested @mmfallacy. I changed it a little bit by passing className through props. Also, in the question I didn't put my real example, so I decided to put it in the answer. Here are my 2 components:

Store.js

import React from 'react';
import Categories from "./Categories";

function Store() {
    return (
        <div>
            <Categories className="store__categories"/>
        </div>
    )
}

export default Store;

Categories.js

import React from 'react';
import Category from './Category';
import bath from '../../img/categories/bath-faucets.svg';

function Categories(props) {
    return (
        <div className={"categories-container " + props.className}>
            <h1 className="heading-primary">Categories</h1>
            <div className="categories">
                <Category url="bath" img={bath} title="BATH & FAUCETS"/>
                <Category url="bath" img={bath} title="BATH & FAUCETS"/>
                <Category url="bath" img={bath} title="BATH & FAUCETS"/>
                <Category url="bath" img={bath} title="BATH & FAUCETS"/>
            </div>
        </div>
    )
}

export default Categories;

Upvotes: 0

mmfallacy
mmfallacy

Reputation: 186

You can get className as a prop of your Products component

function Products({className}){
    
    return(
        <Wrapper className={className}>
             ...
        </Wrapper>
    )
}

Upvotes: 1

Related Questions