-1

I'm trying to add a class to my Card component, so that I can choose the layout while I'm inserting it. But the props is not interpreted in the className, how can I add a css class this way?

Component

 function Card(props) {
        return (
          <div className="d-flex mx-auto {props.layout}" >
            <div className="background my-auto">
              <div className="d-flex justify-content-center">
                <h3>{props.title}</span></h3>
              </div>
              <div className="d-flex h-100">
                <div className="w-100 my-auto">
                  <p>{props.text}</p>
                </div>
              </div>
            </div>
          </div>
        );
      }

In Layout

<Card
 layout="my-green-bg"
 title="my title"
 text="my text"
/>
Artemis
  • 589
  • 1
  • 6
  • 19

2 Answers2

1

Try the following:

<div className={`d-flex mx-auto ${props.layout}`}>

Or without template literals:

<div className={'d-flex mx-auto ' + props.layout}>

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

You can try the below code.

function Card(props) {
    const classes = [ 'd-flex', 'mx-auto' ];
    if (props.layout) classes.push(props.layout);
        return (
          <div className={ classes.join(' ') } >
            <div className="background my-auto">
              <div className="d-flex justify-content-center">
                <h3>{props.title}</span></h3>
              </div>
              <div className="d-flex h-100">
                <div className="w-100 my-auto">
                  <p>{props.text}</p>
                </div>
              </div>
            </div>
          </div>
        );
      }

The other way can be

function Card(props) {
        return (
          <div className={ 'd-flex mx-auto ' + props.layout } >
            <div className="background my-auto">
              <div className="d-flex justify-content-center">
                <h3>{props.title}</span></h3>
              </div>
              <div className="d-flex h-100">
                <div className="w-100 my-auto">
                  <p>{props.text}</p>
                </div>
              </div>
            </div>
          </div>
        );
      }
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17