React 18

Last Updated: 10/14/2023

CSS in JS

  • With CSS-in-JS, we define all the styles for a component alongside its code.
  • Like CSS modules, this provides scoping for CSS classes and eliminates conflicts. It also makes it easier for us to change or delete a component without affecting other components.

Advantages

  • Scoped styles. No name conflicts
  • All the CSS and JS code required to build a component are in one place
  • Easier to delete the component
  • Easier to style based on props and state
  • Styled components
  • Emotion
  • Polished

Using Styled Components

  • Install
npm i styled-components
npm i @types/styled-components
  • Import
import styled from "styled-components";
  • Define styles for elements which return react components. Add interface for props
const List = styled.ul`
  list-style: none;
  padding: 0;
`;

interface ListItemProps {
  active: boolean;
}
const ListItem = styled.li<ListItemProps>`
  padding: 5px 0;
  color: red;
  background: ${(props) => (props.active ? "lightblue" : "lightgray")};
`;
  • Use styled components
<List>
  {items.map((item, index) => (
    <ListItem
      active={index === selectedIndex}
      key={item}
      onClick={() => {
        setSelectedIndex(index);
        onSelectItem(item);
      }}
    >
      {item}
    </ListItem>
  ))}
</List>