Search code examples
javascriptreactjses6-moduleses6-classreact-css-modules

How to nest the class of parent component in child component?


I'm in a learning phase of react and I've been trying to nest style of parent in component in child component via class in react.js. How to do it?

What I've tried until now:

function Card(props) {
    const classes = 'card' + props.className;
    
    return (
        <div className={classes}>
            {props.children}
        </div>
    )
}

export default Card

I applied style on class 'card' in a CSS file.

Parent component JS code:

import Card from './UI/Card';

function ExpenseItem(props){
    return (
        <Card className="expense-item">
            <ExpenseDate date={props.date} />
            <div className="expense-item__description">
                <h2>{props.title}</h2>
                <div className="expense-item__price">{`₹ ${props.amount}`}</div>
            </div>
        </Card>
    )
}

Now, there are various classes in parent component that are styled accordingly. And I'd like to nest those classes in child component for those style to work.

You can see in the code the way I tried to nest the classes, but it isn't working.

const classes = 'card' + props.className;

What am I doing wrong? And how should I correct it?


Solution

  • You missed a space after the card class name, otherwise i don't see any other issues in your code. Try below, hope it works const classes = 'card ' + props.className;