Home > database >  react styled-component nested item's props
react styled-component nested item's props

Time:07-10

My problem is about props. I want to use nested components with props in styled-components. For example:

const MenuItem = ({ item }) => {
const router = useRouter();

const [isOpen, setIsOpen] = useState(false);
const isActive = router?.asPath === item?.path;

return (
    <MenuItemWrapper key={item?.slug} onClick={() => setIsOpen(!isOpen)}>
        <Link href={item?.path}>
            <InnerMenuItem isActive={isActive}>
                {item?.prefix && <Prefix>{item?.prefix}</Prefix>}
                {item?.label}
                {item?.children && <RightArrow isOpen={isOpen} />}
            </InnerMenuItem>
        </Link>
        <Children>
            {
                item?.children?.map((child) => <MenuItem item={child} />)
            }
        </Children>
    </MenuItemWrapper>
);
};

export default MenuItem;

this is MenuItem component. I use MenuItem component as a recursion component.

in styled-component i tried this but it doesnt work. I want to apply different style in Children > InnerMenuItem but it not working

export const Children = styled.div`
display: flex;
flex-direction: column;
margin-left: 65px;


${MenuItemWrapper} {
  font-size: 16px;
  padding: 9px 0;

  &:not(:first-child) {
    border-top:none;
  }
}

${InnerMenuItem} {
  
  ${({ isActive }) => // HOW CAN I USE THIS PROPS HERE
    isActive &&
          css`
            color: orange
    `};
}

`;

CodePudding user response:

from styled components official documentations:
"If the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props."

example :

const Input = styled.input`
  color: ${props => props.inputColor || "palevioletred"};
`;

return(
<Input inputColor="rebeccapurple" />
)

another way is by Extending Styles, example :

const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

return(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

more about styled-components read here

CodePudding user response:

have you tried

${InnerMenuItem} {
       color: ${({isActive})=> isActive ?  'orange' : undefined}
    };
  • Related