How to add "active" class to styled components in React

Viewed 1887

I'm learning React and i just founded about styled-components and i would like to refactor my code into styled components.

Maybe i didn't understand it at all but i'm trying to make add/remove class on "toggle"

For example:

button--active

Here is what i've tried so far:

render() {
    const {active, toggleHamburgerActive } = this.props;
    return (
      <div>
          <HamburgerButtonContainer active={active} onClick={toggleHamburgerActive}/>
     </div>

styles:

const buttonStyles = css`
      border: 1px solid red;
    `;
    
    const getButtonStyles = active => {
      if (active) {
        return hamburgerActiveStyles;
      }
      return buttonStyles;
    };
    
    const hamburgerActiveStyles = css`
      border: 10px solid green;
    `;
    
    export const HamburgerButtonContainer = styled.button`
      ${getButtonStyles}
    `;

@EDIT To make it more clear. active is changing on click but styles are not.

2 Answers

I think you just forgot to destructure your props:

const getButtonStyles = /* this here ---> */({active}) => {
      if (active) {
        return hamburgerActiveStyles;
      }
      return buttonStyles;
    };

const getButtonStyles = /* props is passed here, not only active ---> */props => 

You can access props by passing a callback in an expression as you did.

styled.button`
  ${props => ...} // you passed the callback here, so props is passed to it, not only active
`

Or if you prefer

styled.button`
  ${props => getButtonStyles(props.active)}
`

You haven't called your function using active as a param. And You should organise your code like below to pass the active as a prop.

const HamburgerButtonContainer = ({ onClick, active }) => {
  const buttonStyles = `
  border: 1px solid red;
`;

  const getButtonStyles = (active) => {
    if (active) {
      return hamburgerActiveStyles;
    }
    return buttonStyles;
  };

  const hamburgerActiveStyles = `
  border: 10px solid green;
`;

  const StyledHamburgerButtonContainer = styled.button`
    ${getButtonStyles(active)}
  `;

  return <StyledHamburgerButtonContainer onClick={onClick} />;
};
Related