Home > front end >  Problems with Styled-Components conditional style rendering. I'm not sure what's wrong
Problems with Styled-Components conditional style rendering. I'm not sure what's wrong

Time:10-02

I'm trying to toggle a hamburger menu on and off. I've console logged to check that the boolean values are changing, but the css isn't.

My issue is with 'props.active?' it's working but the '.mobile-menu' class is not changing. I'm not entirely sure what I need to do to get it to work. I've tried to make changes to the style I want to affect because I thought maybe you can't toggle as display, however,f visibility and opacity still aren't changing either.

import { useState } from "react";
import styled from "styled-components";

import logo from "./assets/logo.svg";

const StyledHeader = styled.header`
  ---

  button {
    ---
    span {
     ---
      &:nth-child(even) {
        margin: 5px 0;
      }
    }
  }
  .mobile-menu {
    position: absolute;
    right: 100px;
    top: 100px;
    display: ${(props) => (props.active ? "none" : "block")};
    height: 330px;
    width: 330px;
    background: #e210e2;
    color: white;
    ul {
     ----
    }
  }
`;

const Header = () => {
  const [active, setActive] = useState(false);

  return (
    <StyledHeader>
      <img src={logo} alt="sunnyside logo" />
      <button onClick={() => setActive(!active)}>
        {console.log(active)}
        <span></span>
        <span></span>
        <span></span>
      </button>
      <nav className="mobile-menu" active>
        <ul>
          <li>About</li>
          <li>Services</li>
          <li>Projects</li>
          <li>Contact</li>
        </ul>
      </nav>
    </StyledHeader>
  );
};

export default Header;

CodePudding user response:

Please pass the props in the StyledHeader tag.

Follow the below code:

<StyledHeader active={active}>
....
</StyledHeader>

CodePudding user response:

You're not passing the active prop. You need to pass the active prop to the StyledHeader component to apply the styles like below.

<StyledHeader active={active}>

Updated Code will be like this.

<StyledHeader active={active}>
  <img src={logo} alt="sunnyside logo" />
  <button onClick={() => setActive(!active)}>
    {console.log(active)}
    <span></span>
    <span></span>
    <span></span>
  </button>
  <nav className="mobile-menu" active>
    <ul>
      <li>About</li>
      <li>Services</li>
      <li>Projects</li>
      <li>Contact</li>
    </ul>
  </nav>
</StyledHeader>
  • Related