Zaka awan
Zaka awan

Reputation: 21

How to use same component in React multiple time but with different CSS on different pages

I have created a separate file of some data and importing in different files. With the map function, I am printing this data in the

  • tag. But want to use this data on different pages with different CSS like in some pages I need color changes or different font size. No event requires. Just want to print data of same component but with different CSS on every page.

        `const Truck = [
        {
            icon: <i className="fa fa-truck fa-flip-horizontal"></i>,
            text: "Door pick-up and delivery",
        },
        {
            icon: <i className="fa fa-truck fa-flip-horizontal"></i>,
            text: "Heavy weight shipments",
        },
        {
            icon: <i className="fa fa-truck fa-flip-horizontal"></i>,
            text: "Same day delivery in city limits",
        },
    ]
    export default Truck`................
    
    Map function
    
    }`export const UlServicesItems = () => {
        return (
            <div id="UlMarginTop">
                {Truck.map((item, index) => {
                    return (
                        <div id="txt">
                            <li key={index} className="iconTruck">{item.icon}</li>
                            <li key={index} className='newId'>{item.text}</li>
                        </div>
    
                    )
                })}
            </div>`enter code here`
        )
    

    Upvotes: 0

    Views: 1755

  • Answers (1)

    axtck
    axtck

    Reputation: 3965

    You could define some sort of theme and pass it as props to your component.

    First create some CSS classes.

    .bg-green {
      background-color: green;
    }
    
    .bg-red {
      background-color: red;
    }
    
    .big-text {
      font-size: 20px;
    }
    

    In your parent component, define themes and pass it as props to the components.

    import "./styles.css";
    import Card from "./Card";
    
    export default function App() {
      const theme = {
        backgroundclass: "bg-green",
        textclass: "big-text"
      };
    
      const theme2 = {
        backgroundclass: "bg-red",
        textclass: "big-text"
      };
    
      return (
        <div className="App">
          <Card theme={theme} />
          <Card theme={theme2} />
        </div>
      );
    }
    

    In your child component, use the theme prop and set the values to the corresponding elements.

    export default function Card({theme}) {
      return (
        <div className={theme.backgroundclass}>
          <p className={theme.textclass}>hello</p>
        </div>
      );
    }
    

    Sandbox link

    Upvotes: 2

    Related Questions