In my HTML I have a lot of repeated elements with quite a few attributes each and most of them are the same. It's taking up a lot of space and I could clean up the code if I could just set the attributes as a variable and use that variable in all my elements. So is there a way to do this?
For example one of my elements look like this,
<button className='btn btn-secondary dropdown-toggle' style={{ margin: "5px" }} type='button' data-bs-toggle='dropdown' aria-expanded='false'>
Delete
</button>
And there are at least 10 other buttons with the exact same set of attributes and takes up almost 100 lines worth of space. Is there a way I can set the attributes in one place then apply it to every element to save space?
CodePudding user response:
If you are reusing a collection of html attributes, here are two ways you could handle this:
- Save the attributes into an object and spread the object onto each
<button>
that uses them. - Create a
<CustomButton>
component and encapsulate the shared attributes in the component. Because each attribute is exposed as a prop in the component interface, each prop/attribute has a default value but can be overwritten if necessary.
// #1
const defaultButtonProps = {
className: "btn btn-secondary dropdown-toggle",
style: { margin: "5px" },
type: "button",
"data-bs-toggle": "dropdown",
"aria-expanded": "false"
};
export default function App() {
return (
<div className="App">
<div>
{/* #1 */}
<button {...defaultButtonProps}>Delete</button>
<button {...defaultButtonProps}>Save</button>
</div>
<div>
{/* #2 */}
<CustomButton />
<CustomButton>Save</CustomButton>
</div>
</div>
);
}
// #2
const CustomButton = ({
className = "btn btn-secondary dropdown-toggle",
style = { margin: "5px" },
type = "button",
dataBsToggle = "dropdown",
ariaExpanded = "false",
children = "Delete"
}) => {
return (
<button
className={className}
style={style}
type={type}
data-bs-toggle={dataBsToggle}
aria-expanded={ariaExpanded}
>
{children}
</button>
);
};
CodePudding user response:
if you want to clean up the code and wants to remove the repeated attribute use the 'class name'
.submit-btn {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<body>
<button >Button</button>
<input type="button" value="Input Button">
</body>
class name will access the all properties accordingly