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?
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.