Search code examples
reactjsstyled-components

Is there any way I can style the nested component?


Here's my code.

/*Default Styled Component*/

import styled from "styled-components";
export const MenuWrapper = styled.ul`
border: 1px solid blue;
`

export const MenuList = styled.li`
color: blue;
`

export const Menu = (
  <MenuWrapper>
   <MenuList>1</MenuList>
   <MenuList>2</MenuList>
   <MenuList>3</MenuList>
  </MenuWrapper>
);




/* This is where I tried to restyle */

import styled from 'styled-components';
import {
  Menu,
  MenuWrapper,
  MenuList,
} from '../src/components/Menu.style';

const StyledMenu = styled(Menu)`
${MenuWrapper} {
  border: 1px solid green;
}
${MenuList} {
  color: green;
}

What I want to do is to create a default styled component with multiple elements in it and restyle according to my needs by using 'styled(Menu)' and adding ${MenuWrapper} ${MenuList} as selectors for nested elements but they all don't seem to work... Anyone can help..? Thank you in advance...


Solution

  • I see several issues here, but in the first place it seems like the problem is caused by the fact that you're not attaching the className prop to what's inside Menu.

    See https://styled-components.com/docs/basics#styling-any-component and this Codesandbox: https://codesandbox.io/s/sweet-carlos-vt165s