Component Styles
7 minutes of reading
Basic Approach
In React, you can add CSS class names to an HTML element by using the className attribute. In addition, a custom component doesn’t have the className attribute by default, you have to pass the class names as props and add them to the className attribute of the inner HTML elements.
1 2 3 4 5 6 7 8
const Card = (props) => { const classes = "card " + props.className; return <div className={classes}>{props.children}</div>; }; function App() { return <Card className="classic">React Rocks</Card>; }
Add the following style in src/index.css or other global stylesheets.
1 2 3
.classic { background-color: aqua; }
It is common for CSS classes to depend on the component props or state. If you often find yourself writing code like the following, the classnames package can simplify it.
1 2 3 4 5 6 7 8 9 10 11
const Card = (props) => { let classes = "card"; if (props.isClassic) { classes += " classic"; } return <div className={classes}>{props.children}</div>; }; function App() { return <Card isClassic={true}>React Rocks</Card>; }
Styled Component
This is a Node package for creating a React component by attaching styles to a particular HTML element. To use it, run the following command in the terminal to install it in your project.
$ npm install styled-components
You might haven't seen the unusual syntax styled.button`...` before, this is actually called the template literal in JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import styled from "styled-components"; const StyledButton = styled.button` padding: 2rem; color: ${(props) => (props.invalid ? "red" : "#000")}; box-shadow: 0 0 4px rgba(0, 0, 0, 0.26); @media (min-width: 700px) { width: auto; } &:focus { outline: none; } `; function App() { <StyledButton className="classic" invalid={true}> React Rocks </StyledButton> }
To add class(es) to a component, you can do it the normal way and styled-components will direct the class to the element for you. You can also use props within the template literal.
In the background, this package encloses the styles within the tagged template literal to two automatically generated unique classes so that when these styles are added to the global style sheet, styles won’t leak to other components.
CSS Modules