Search code examples
reactjstypescriptstyled-components

Trying to apply a class to a styled-component for an onclick event


In using standard JSX and CSS, I can add a className attribute with some logic to add a class name based on a boolean value, but when using styled-components, this doesn't appear to be as easy. This is what I have at the moment:

Menu.tsx

interface IMenuProps {
  showMenu: boolean;
  menuToggle: () => void;
}

const Menu: React.FC<IMenuProps> = ({ showMenu, menuToggle }) => {
  return (
    <MenuWrapper onClick={menuToggle} {showMenu ? "showMenu" : ""}>
      ...

At the moment, there's a red line under the showMenu within the ternary statement.

'...' expected.

Hopefully you can see what I'm trying to do here.


Solution

  • You forgot to add className.

    const Menu: React.FC<IMenuProps> = ({ showMenu, menuToggle }) => {
      return (
        <MenuWrapper onClick={menuToggle} className={showMenu ? "showMenu" : ""}>

    BTW:

    If there isn't any logic inside your component you can write it as

    const Example: FC = () => (
      <div>
        <h1>Example</h1>
      </div>
    );