I'm building a reusable Button component in React whose background image is an image of a button (e.g. PNG export from Figma) and is customizable.
My current implementation is as follows -
Button.js
const Button = ({ url }) => {
const inlineStyle = {
backgroundImage: `url(${url})`
}
return (
<button
type='submit'
style={inlineStyle}
className='button'
/>
)
}
Button.css
.button {
width: 100%;
padding: 30px 0;
border: none;
background-color: rgba(0, 0, 0, 0);
background-position: 50% 50%;
background-size: contain;
background-repeat: no-repeat;
cursor: pointer;
}
But, the problem is this doesn't support all kind of button sizes. If a button is really wide and short in height, I'll have to readjust it again with another className
like so -
const Button = ({ url, modifierClass }) => {
const inlineStyle = {
backgroundImage: `url(${url})`
}
return (
<button
type='submit'
style={inlineStyle}
className={`button ${modifierClass}`}
/>
)
}
.modifier {
max-width: 300px;
}
If it is a narrow button -
.modifier {
max-width: 140px;
}
My question is how do I code the Button component and its CSS so that it supports all kind of background image button shape; narrow, wide or tall on a fixed size?
CodePudding user response:
I think I got what are you looking for. Change background-size: 'contain'
to background-size: 'cover'
and give it max-width: 100px
(100px
for example) and by using padding
, height
, min-height
or etc., you get the same result and background doesn't need to be readjusted.
.ButtonComponent {
width: 100%;
max-width: 100px; /* Max width for the button */
padding: 30px 0; /* `min-height` / `height` */
border: none;
background-color: rgba(0, 0, 0, 0);
background-position: 50% 50%;
background-size: cover; /* Change `contain` to `cover` */
background-repeat: no-repeat;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}
CodePudding user response:
With Ali Bahaari's help I figured out I can use max-width
to control the Button
's size.
I can accept size
as prop and put it as max-width
in inline style,
const Button = ({ url, size }) => {
const inlineStyle = {
backgroundImage: `url(${url})`,
maxWidth: size
}
return (
<button
type='submit'
style={inlineStyle}
className='button'
/>
)
}
and use the component like <Button size='100px' />
. This won't support responsiveness as inline style doesn't support media queries. If adjusting size per screen is needed, I'll just have to use the way in my question.