Home > OS >  How to display different button on different component while mapping through a common component in R
How to display different button on different component while mapping through a common component in R

Time:09-16

I have created a component which basically generates a card which includes card title,card description and a button. Now when I map through an array on a different component to generate those cards I want the button to be different on different components. Like on home page the button should say Update, on other page the button should say Delete. How can I acheive that? Here is the component which generates card.

import React from 'react';
import { Card } from 'react-bootstrap';

const InventoryItem = ({ product }) => {
    const { productName, productImage, productPrice, productQuantity, productSupplier, productDetails } = product;
    return (
        <div className='col-12 col-md-6 col-lg-6'>
            <Card className='h-100 items-card d-block d-md-block d-lg-flex flex-row align-items-center border border-0'>
                <div className='text-center card-image-container'>
                    <Card.Img variant="top" src={productImage} className='card-image img-fluid' />
                </div>
                <Card.Body className='card-details'>
                    <Card.Title>{productName}</Card.Title>
                    <Card.Text>{productDetails}</Card.Text>
                    <div className='d-lg-flex align-items-center justify-content-between mb-3'>
                        <p className='mb-0'>Price: ${productPrice}</p>
                        <p className='me-2 mb-0'>Stock: {productQuantity}</p>
                    </div>
                    <div className='d-flex align-items-center justify-content-between'>
                        <p className='mb-0'>Supplier:{productSupplier}</p>
                        <button className='btn btn-dark'>Update</button>
                    </div>
                </Card.Body>
            </Card>
        </div>
    );
};

export default InventoryItem;

CodePudding user response:

Pass the button text as a prop to the component, so consuming code can speficy the text for the button.

Add it as a prop:

const InventoryItem = ({ product, buttonText }) => {

And use it in the button:

<button className='btn btn-dark'>{buttonText}</button>

Then when using the component, pass the prop:

<InventoryItem product={someProductObject} buttonText="Update" />

or with a conditional value:

<InventoryItem product={someProductObject} buttonText={someCondition ? "Update" : "Delete"} />

CodePudding user response:

You can define a condition for the button basaed on the page you are: window.location.href return the string href.

const MyButton= window.location.href=='Home'
? <button> HOME</button>
: <button> UPDATE</button>

Hope that answer your question, Mauro

  • Related