Search code examples
reactjsstyled-components

Styled Component (button) not working with onClick


I have one styled component which is button. I was trying to use onClick method on this exported component but this event (onClick) is completely dead. I have no idea where is problem. ( additionally i'm using framer motion)

import styled from 'styled-components';
import { motion } from 'framer-motion';

const StyledButton = styled(motion.button)`
  background: #3939be;
  color: #fff;
  border: none;
  border-radius: 19px;
  height: 38px;
  width: fit-content;
  padding: 0 16px;

  font-weight: 600;
  font-size: 0.75rem;
  cursor: pointer;

  @media screen and (min-width: 640px) and (min-height: 440px) {
    height: 44px;
    border-radius: 22px;
  }
`;

const PillButton = ({ children }) => {
  return (
    <StyledButton
      whileTap={{ scale: 0.95, transition: { duration: 0.1 } }}
      whileHover={{ scale: 0.95, transition: { duration: 0.1 } }}
    >
      {children}
    </StyledButton>
  );
};

export default PillButton;
<PillButton
   onClick={() => {
   setActiveTab('test');
   }}
   > 
</PillButton>

Solution

  • You need to pass down the onClick method

    
    const PillButton = ({ children, onClick }) => {
      return (
        <StyledButton
          whileTap={{ scale: 0.95, transition: { duration: 0.1 } }}
          whileHover={{ scale: 0.95, transition: { duration: 0.1 } }}
          onClick={onClick}
        >
          {children}
        </StyledButton>
      );
    };
    
    <PillButton
       onClick={() => {
       setActiveTab('test');
       }}
       > 
    </PillButton>