I was trying to add different styles for a component in react nect.js. Below I’ve mentioned my code for button component
import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{props.text}</button> </div> ) } export default Button;
I have to use this button component two times in my webpage, but with different styles.(for example, I want first component with blue background and another one with green background. Can anyone help me with this?
import Button from "@/components/button";
function Home() {
return (
<div className="home">
<div className="actions">
<Button className="live" text = "Go Live"/>
<Button className="userAdd" text = "Add users"/>
</div>
</div>
);
}
export default Home;
I tried adding different classname for the button component and adding style to that class. But no result.
2
Answers
First, you can make the
Button
component use the passed inclassName
prop, adding it to the base class. You can decide whether to apply these additional classes to the<button>
or the parent<div>
.Then, you can add more classes to
button.module.css
:Finally, pass more classes in the
Home
component.A couple of approaches:
Approach 1
Pass in a colour as a prop to
Button
. Here I have a base class called.button
(containing, say, padding/margin information for all types of button) which I’m combining with the colour class in an array in theButton
component, and passing that to the buttonclassName
attribute.Note: you could use the
classnames
utility library instead of the array if your class composition gets too unwieldy for an array.button.modules.css
Button.jsx
Approach 2
Very similar but using
composes
to use the base.button
class within each colour class to inherit its properties. This means that you don’t have to use an array to build the className.button.modules.css
Button.jsx