6

I have a styled component which looks like:

import styled from 'styled-components';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';

export const CategoryList = styled(List)`
`;
//this is what i want to change
export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;
`;

export const CategoryListItemText = styled(ListItemText)`
  padding-left: 5px;
`;

export const ListItemHeading = styled(ListItem)`
  background-color: #f4f4f4;
`;

How can I use siblings in this case & + & ?

I want to achieve something like :

li + li {
border-top: 1px solid red;
}

How can I achieve this?

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Ackman
  • 1,562
  • 6
  • 31
  • 54

1 Answers1

6

This is done the same way as in SCSS with &:

export const CategoryListItem = styled(ListItem)`
  border-top: 2px solid #f4f4f4;

  & + & { // this will work for <CategoryListItem /><CategoryListItem />
    border-top: 1px solid red;
  }
`;

You can also style with html elements but the code above is a better practice

& + li { // this will work for <CategoryListItem /><li />
  border-top: 1px solid red;
}

Basically you can do any nesting with &

& li { // this will work for <CategoryListItem><li /></CategoryListItem>
}
& li.test { // this will work for <CategoryListItem><li class="test" /></CategoryListItem>
}

You can read it up in the official docs: https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting

Dimitri L.
  • 4,499
  • 1
  • 15
  • 19
  • Thank you for your time. Can you help me interpret this code? what does & and + mean and do? – Ackman Jan 15 '20 at 19:13
  • `&` is the "nested parent selector" https://stackoverflow.com/a/11084798/4668136 . `+` is the "followed by selector" https://www.w3schools.com/cssref/sel_element_pluss.asp . I have already described how the selectors will behave in your case in the comments – Dimitri L. Jan 16 '20 at 20:04