CSS Techniques for Smooth Transitions

When the hamburger icon is pressed, a menu appears over the current page with CSS from Glamor. The menu slides in perfectly from the right side of the screen, but I am having trouble getting it to slide out when any part of the menu is clicked.

I have defined the animation for sliding out (animateOut), but I need assistance in implementing the code to switch between animating in and out based on where the user clicks:

  • Clicking on the hamburger menu -> menu slides in from the right
  • Clicking anywhere inside the menu container -> menu slides out to the right

HamburgerMenu.js

CSS

const cssHamburgerMenuIcon = css({
    position: 'absolute',
    height: 20,
    width: 20,
    right: 20,
    marginTop: 20,
})

const animateIn = css.keyframes({ 
    '0%': {
        transform: 'translateX(100%)'
    },
    '100%': {
        transform: 'translateX(0%)'
    }
})

const animateOut = css.keyframes({ 
    '0%': {
        transform: 'translateX(0%)'
    },
    '100%': {
        transform: 'translateX(100%)'
    }
})

const cssHamburgerMenu = css({
    display: 'flex',
    position: 'absolute',
    flexDirection: 'column',
    height: '100%',
    width: 250,
    right: 0,
    top: 0,
    zIndex: 1,
    color: 'white',
    backgroundColor: hamburgerGrey,
    fontFamily: 'Century Gothic',
    fontSize: '19px',
    // animation
    animation: `${animateIn} 0.5s`,
})

const cssHamburgerList = css({
    listStyleType: 'none',
    lineHeight: '47px',
})

const cssHamburgerListItem = css({

})

"CODE"

class HamburgerMenu extends Component {
    constructor(props) {
    super(props)
    this.state = {
        menuVisible: false,
    }
}

    render() {
        const menuVisible = this.state.menuVisible

        return(
            menuVisible ?
            <div className={cssHamburgerMenu} onClick={() =>this.setState({ menuVisible: false })}>              
                <ul className={cssHamburgerList}>
                    <li className={cssHamburgerListItem}>Home</li>
                    <li className={cssHamburgerListItem}>News</li>
                    <li className={cssHamburgerListItem}>About us</li>
                    <li className={cssHamburgerListItem}>More</li>
                </ul>
            </div>
            : (
            <img 
                className={cssHamburgerMenuIcon}
                src={HamburgerMenuIcon}
                onClick={() => this.setState({ menuVisible: true})
                }
            />  
            )
        )
    }
}   

export default HamburgerMenu

Answer №1

Here is an alternative suggestion:

  • Start by setting the default translateX of the menu to 100%

  • Create a new class (e.g. open) with translateX set to 0%

  • Apply a smooth transition effect to the menu using "transition: all 0.5s ease-in-out;"

  • To open or close the menu, simply add or remove the (open) class as needed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

If you encounter an 'Invalid contract call' error while using useDapp's useContractCall in React

Within a React component, I am attempting to retrieve the function "paused" from a contract deployed on the Rinkeby testnet. Utilizing the useDapp () hook called "useContractCall", I invoke the contract function within a custom hook: import { ethers } from ...

Exploring methods to retrieve the current state of Redux reducers

When working with a redux reducer, is there a way to change only one property of the initial state? For instance: const INITIAL_STATE = { signInInfo: { signin: false, name: "", email: "", ... }, changePassword: { status: fals ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

What is the best way to transform an array of lists into a neatly organized state?

I recently received a list of breweries from an API call and I am trying to format it into my React state container. Here is what I have so far: state = { breweries: [ {name: Foo, long: 45, lat: -39.239}, ...

Experience the visually stunning React Charts line chart featuring grouped labels such as months and weeks

Can you create a line chart in recharts with grouped points, such as displaying 6 months data series per day for about 180 days? Each point on the chart represents a day, but I want the X-axis labels to show the corresponding month like Jan, Feb, Mar, Apr, ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Exemplary CSS Text Alignment When Vertical Align is Exceptional

I'm currently working on a menu where some text needs to be aligned vertically with the property vertical-align:super. However, I am facing an issue where this particular item with "super" text is not aligning properly with the other items. Below is ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

The variable declared in the useState hook is not being properly updated within the callback function

const ModifiedTweet = ({ tweet, checkedList, setCheckedList }) => { const [isChecked, setChecked] = useState(false); useEffect(() => { if (checkedList.length === 0) { setChecked(false); } }, [checkedList, isChecked]); return ( ...

What is the process for installing the shadcn component library with yarn or npm?

My latest project involves creating a Notion-inspired app using Next.js and the shadcn/ui library from [https://ui.shadcn.com/]. I attempted to add shadcn/ui to my project using npm and yarn, but encountered some difficulties along the way. ...

The combination of React Vite and SockJS Client has encountered a failure in all transport

My current project is utilizing react + vite without any proxy configuration. I am attempting to use webstomp-client and sockjs to establish a connection with a websocket server that is supported by Springboot using SockJS. The backend Springboot server w ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

At times, PHP mail usage may result in certain $_POST arrays being unexpectedly empty

I've encountered an issue while using the php mail function to send data from a html form. The mail function is functioning correctly and I receive the email upon form submission, but occasionally I receive empty arrays in the email content. Here is ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

Is there a way to integrate the CopyWebpackPlugin into a create-react-app setup without having to eject?

Currently, I am in the process of developing a React application and one of my objectives is to transfer all image files from the source location to the build destination. To accomplish this task, I have been studying various tutorials and have successfull ...

Reacting to each change event, Angular dynamically loads new autocomplete options

I am facing an issue with my form where users need to select a company using mat-select-search. Upon selection, an API call is made with the selected company ID to fetch users from that company for the autocomplete feature in recipient fields. The process ...

We're unable to locate the module: Error - The file 'react-bootstrap-validation' cannot be resolved

Query I am encountering an error message in webpack that says: Error: Cannot find module 'react-bootstrap-validtion' at Function.Module._resolveFilename (module.js:339:15) at Function.Module._load (module.js:290:25) at Module.requir ...

Calculating the combined cost of items in the shopping cart

I encountered a small problem while working on my project. I'm trying to calculate the total price of all items in the cart by summing them up, but my mind is drawing a blank at the moment. Below is the code snippet I am currently using: const { ca ...