How to style the last child in React Native with styled components

Viewed 5076

How to style the last child in React Native with styled components?

It does not work:

&:last-child {
   border-bottom-width: ${normalize(1.5, true)};
   border-bottom-color: ${p => p.theme.RED};
}

Below is a sample code where I want to add (border-bottom-color) everywhere except the last child.

export const ListItem = styled.TouchableOpacity`
  ${props =>
    props.border &&
    `
    border-bottom-width: ${normalize(1.5, true)};
    border-bottom-color: ${props.theme.UI_LIST_COLOR};
  `};

  padding: ${s(2, 14, 1)};
`;

Anyone can help me with it? Thanks in advance!

1 Answers

I'm not sure of your complete setup, nor the details of your props object, but here is a minimal working example that should provide you some direction in getting your implementation working.

const ListItem = styled.li`
  ${props => props.border && `
    border-bottom: solid;
    border-bottom-width: 3px;
    border-bottom-color: ${props.theme.UI_LIST_COLOR};
    &:last-child {
      border-bottom-width: 6px solid;
      border-bottom-color: ${props.theme.RED};
    }
  `}
`;

function App({list}) {
  const theme = {UI_LIST_COLOR: 'blue', RED: 'red'}
  
  const listItems = list.map((item) =>
    <ListItem theme={theme} border={true} key={item}>
      {item}
    </ListItem>
  );
  
  return ( 
    <section className="todoapp">
        <ul className="todo-list">
          {listItems}
        </ul> 
    </section>
  );
}

const sampleList = ['LI 1', 'LI 2', 'LI 3', 'LI 4']
ReactDOM.render( < App list={sampleList} / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.1/styled-components.min.js"></script>

Related