Home > Mobile >  Change state in function component react
Change state in function component react

Time:06-28

I am new to React and being held back by a seemingly simple task. I've got a Header component nested within which is a HamburgerButton component. Clicking the latter should make a sidenav appear but for now I would like the icon to change from the 'hamburger' to the big 'X'. Here is my parent component:

import { MyMoviesLogo } from 'components/Icons';
import HamburgerButton from 'components/HamburgerButton/HamburgerButton'; 

import styles from './Header.module.css';


const Header = (): JSX.Element => {
  const [isActive, setIsActive] = useState(false);
  return (
    <header className={styles.header}>
      <MyMoviesLogo className={styles.headerIcon} />
      <HamburgerButton
      isActive={false}
      />
    </header>
  );
};

export default Header;

And here is the HamburgerButton

import styles from './HamburgerButton.module.css';

type HamburgerButtonProps = {
    isActive: boolean;
    onClick?: () => void;
};

const addMultipleClassNames = (classNames: string[]): string => classNames.join(' ');

const HamburgerButton = ({ isActive, onClick }: HamburgerButtonProps): JSX.Element => {

    return (
        <div className={isActive ? addMultipleClassNames([styles.hamburger, styles.active]) : styles.hamburger} onClick={onClick}>
            <div className={styles.bar}></div>
            <div className={styles.bar}></div>
            <div className={styles.bar}></div>
        </div>
    );
}

export default HamburgerButton;

Here's my HamburgerButton.module.css file:

.hamburger {
    cursor: pointer;
    display: block;
    width: 25px;
}

.bar {
    background-color: var(--hamburger-button-global);
    display: block;
    height: 3px;
    margin: 5px auto;
    transition: all 0.3s ease-in-out;
    width: 25px;
}

.hamburger.active .bar:nth-child(2) {
    opacity: 0;
}

.hamburger.active .bar:nth-child(1) {
    transform: translateY(8px) rotate(45deg);
}

.hamburger.active .bar:nth-child(3) {
    transform: translateY(-8px) rotate(-45deg);
}

Manually changing the isActive prop to false verifies that the styling is applied as required. My question is, how could I make it so when I click the icon its state gets toggled? I am familiar with React hooks like useState but can't quite put something together.

Any help would be greatly appreciated.

Thank you.

P.S.: It's probably obvious but I am using TypeScript.

CodePudding user response:

You should use your onClick prop from your <HamburgerButton /> to change the parent state.

<HamburgerButton isActive={isActive} onClick={() => { setIsActive(oldState => !oldState) } />
  • Related