I have a react component that has an h3
with dark gray text color. I would like to reuse the component in a place where the background color is also dark gray, so I need to change the h3
text color to something lighter.
This is how the component was before I needed to change the text color in some areas:
// other imports
import styles from "./styles/subheader.module.css"
export default function Subheader(props) {
return (
<Container>
<h3 className={styles.h3}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
CSS:
.h3 {
font-family: var(--font-family);
font-size: var(--h3-font-size);
text-align: center;
color: rgb(33, 37, 41);
margin-top: 2rem;
}
.headerUnderline {
width: 100px;
height: 4px;
background-color: rgb(219, 190, 157);
margin: 0 auto;
border-radius: 2px;
margin-bottom: 2rem;
}
I tried this which didn't work:
<Subheader text="PRODUCTS" style={{color: "rgb(219, 190, 157)"}} />
So I tried passing props and changed my component:
//other imports
import styles from "./styles/subheader.module.css"
export default function Subheader(props) {
return (
<Container>
<h3 className={styles.h3 " " props.lightText ? styles.lightText : styles.darkText}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
And changed CSS:
.h3 {
font-family: var(--font-family);
font-size: var(--h3-font-size);
text-align: center;
margin-top: 2rem;
}
.lightText {
color: rgb(219, 190, 157);
}
.darkText {
color: rgb(33, 37, 41);
}
And used like:
// both render light text with no .h3 styling like centered text
<Subheader text="WE DELIVER" lightText={true} />
<Subheader text="PRODUCTS" lightText={false} />
But that didn't work either.
CodePudding user response:
It will work if you change your h3
className to template string:
<h3 className={`${styles.h3} ${props.lightText ? styles.lightText : styles.darkText}`}>{props.text}</h3>
or at least last part of it:
<h3 className={styles.h3 " " `${props.lightText ? styles.lightText : styles.darkText}`}>{props.text}</h3>
Here you can find a lot of great examples how to add multiple classnames: How to add multiple classes to a ReactJS Component?
CodePudding user response:
You can use style
prop like you did here:
<Subheader text="PRODUCTS" style={{color: "rgb(219, 190, 157)"}} />
But notice that you're not passing the style
prop to an element, but to a component, so, like text
, it can be accessed inside the component on the props
object (i.e. props.style
).
This how you can access style
:
export default function Subheader(props) {
return (
<Container>
<h3 style={props.style} className={styles.h3}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
Live example: Code Sandbox