0

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;
4
  • can you show the Products component? Commented Jul 4, 2020 at 9:44
  • yes its possible Commented Jul 4, 2020 at 12:09
  • Why not, You can assign css class to a react component eg. className={styles.productsuvs} OR className="productsuvs" Commented Jul 5, 2020 at 4:23
  • Just assigning class using className doesn't work for some reason. Commented Jul 5, 2020 at 9:47

2 Answers 2

1

You can get className as a prop of your Products component

function Products({className}){
    
    return(
        <Wrapper className={className}>
             ...
        </Wrapper>
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used this approach though I had to pass it through the props.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.