Home > Enterprise >  How to nest the class of parent component in child component?
How to nest the class of parent component in child component?

Time:06-22

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?

CodePudding user response:

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;

CodePudding user response:

Just one note, this will make your components dependent on each other. One of best things about React is that it allows you to have separation of concerns. So Card component is doing Card component staff, displaying some information and needs not be dependent on a parent in this case ExpenseItem.

One way to do it is to use styled-components.

  • Related