Basically, we don't want that one specific component styles affect another components unlike our intention.
There is a few methods to figure out this.
With inline style, we can apply styles to specific one element.
<label style={{color: !isValid ? 'red' : 'black'}}>Course Goal</label>
you also can give ternary condition to apply styles.
But, Inline styles have highest priority in order of css, so It is not recommended.
Like we do in vanilla javascript commonly, we also can add classes for specific style in JSX syntax
<div className={`form-control ${!isValid ? "invalid" : ""}`}>
.form-control.invalid input {
border-color: red;
background: red;
}
.form-control.invalid label {
color: red;
}
With javascript template literal, we can add ternary condition in className.
However, this also may occur duplicated styles if you use same class name to other components unconsciously.
Use a package - styled components
npm install --save styled-components
Import it in component which you want to apply and invoke with weird back ticks syntax.
In the backticks, you can copy and paste your style from external stylesheet. you don't need selector and when you use Pseudo class or other long selectors, just attach '&' ampersand instead of class name.
import styled from "styled-components";
const Button = styled.button`
font: inherit;
padding: 0.5rem 1.5rem;
border: 1px solid #8b005d;
color: white;
background: #8b005d;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
cursor: pointer;
&:focus {
outline: none;
}
&:hover,
&:active {
background: #ac0e77;
border-color: #ac0e77;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
`;
<FormControl className={!isValid && "invalid"}>
<label>Course Goal</label>
<input type="text" onChange={goalInputChangeHandler} />
</FormControl>
<FormControl invalid={!isValid}>
const Formcontrol = styled.div`
.
.
& input {
display: block;
width: 100%;
border: 1px solid ${(props) => (props.invalid ? "red" : "#ccc")};
background: ${(props) => (props.invalid ? "salmon" : "transparent")};
font: inherit;
line-height: 1.5rem;
padding: 0 0.25rem;
}
.
.
`
Simply add media queries under the style which you wanna apply to
Now you have three choices.
One is not using any methods while you're ensuring there is no duplication of style class
Another is using styled-component package.
The other is using css modules
If you installed react with create-react-app, React already configured the setting of css module.
Follow these steps.
1. import css stylesheet with custom name.
import styles from "./Button.css";
2. Insert a word 'module' between your stylesheet name and extension.
ex. Button.module.css
3. You can access any css property with your custom imported stylesheet name. Then , your css module will change that class name as unique characters.
<button type={props.type} className={styles.button} onClick={props.onClick}>
<div
className={`${styles["form-control"]} ${!isValid && styles.invalid}`}
>