简体   繁体   中英

how to change text of button based on media query

I want to change text "proceed to payment" to "Buy now", if media query is 767px

const CheckoutButton = styled(GreenButton)
    text-transform: none;
    font-family: 'Poppins', Arial, Helvetica, sans-serif;
    font-weight: 500;
    height: 40px ;
    font-size: 1rem;
    padding: 6px 20px !important;
    margin-left: 100px;

<CheckoutButton disabled={isSubmitting || disabled} onClick={handleSubmit} type="submit">Proceed to Payment</CheckoutButton>

Possible Solution

Add/Remove inline text elements as per media query

Solution

React

<CheckoutButton disabled={isSubmitting || disabled} onClick={handleSubmit} type="submit"><span className="desktop-text">Proceed to Payment</span><span className="mobile-text"></span></CheckoutButton>

CSS

.mobile-text {display: none;} @media screen and (max-width: 767px) {.desktop-text {display: none;}.mobile-text {display: inline-block;}

In pure CSS, you can add the button's label via a pseudo-element:

 .testbutton::before { content: 'buy now'; } @media (min-width: 767px) {.testbutton::before { content: 'proceed to payment'; } }
 <button class='testbutton'></button>

That being said, I'm not thrilled about having the button label in the CSS. In React, I always have a "uiStore" that allows components to keep track of the screen size and brakepoints, if they must. Then you could have something like:

const CheckoutButton = props => {
  const { layout } = uiStore
  return (
    <button>
      {layout === 'mobile' ? 'Buy now' : 'Proceed to payment'}
    </button>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM