Tips for maintaining a stationary element with fluctuating height positioned at the bottom in React

I am trying to create a fixed element with dynamic height, meaning its size changes when the browser window is resized. You can see an example of what I'm talking about here: https://stackblitz.com/edit/react-yuqarh?file=demo.tsx

This element acts like a menu and should:

  • open automatically on first load (working)
  • hide when the user clicks "hide" (partially working)
  • open when the user clicks on a menu icon (working)

When the element is hidden, I use a negative bottom value to hide it. However, this value remains fixed even as the height of the element changes due to browser resizing, causing the element to disappear.

Just to clarify, this element is actually a search component with some input fields, but I've simplified it for this example.

Answer №1

To reposition this element outside the visible area, consider using transform: translateY(100%); instead of setting bottom to -125px

import * as React from 'react';
import MenuIcon from '@mui/icons-material/Menu';
import { IconButton, Box, Button, Grid } from '@mui/material';
export default function Demo() {
  const [transform, setTransform] = React.useState('0px');

  return (
    <div style={{ position: 'fixed', bottom: '0px', transform: `translateY(${transform})` }}>
      <div>
        <IconButton onClick={() => setTransform('0')}>
          <MenuIcon />
        </IconButton>
        <Box>
          <Grid container>
            <Box
              sx={{ height: '50px', width: '150px', backgroundColor: 'red' }}
            ></Box>
            <Box
              sx={{ height: '30px', width: '150px', backgroundColor: 'grey' }}
            ></Box>
          </Grid>
          <Button onClick={() => setTransform('calc(100% - 40px)')}>hide</Button>
        </Box>
      </div>
    </div>
  );
}

Answer №2

This code snippet is all set to go

import * as React from 'react';
import MenuIcon from '@mui/icons-material/Menu';
import { IconButton, Box, Button, Grid } from '@mui/material';
export default function Showcase() {
  const [open, setOpen] = React.useState(true);
  return (
    <div style={{ position: 'fixed', bottom: 0 }}>
      <div>
        <IconButton onClick={() => setOpen(!open)}>
          <MenuIcon />
        </IconButton>
        {open && (
          <Box>
            <Grid container>
              <Box
                sx={{ height: '50px', width: '150px', backgroundColor: 'red' }}
              ></Box>
              <Box
                sx={{ height: '30px', width: '150px', backgroundColor: 'grey' }}
              ></Box>
            </Grid>
          </Box>
        )}
      </div>
    </div>
  );
}

Answer №3

Conditional rendering is an important aspect to consider in solving the issue at hand. If we opt not to implement it, the alternative solution would involve extracting the burger menu from the disappearing div. Here's how you can achieve this:

export default function Demo() {
  const [showMenu, setShowMenu] = React.useState('0px');

  return (
    <>
      <IconButton onClick={() => setShowMenu('0px')}>
        <MenuIcon />
      </IconButton>
      <div style={{ position: 'fixed', bottom: showMenu }}>
        <div>
          <Box>
            <Grid container>
              <Box
                sx={{ height: '50px', width: '150px', backgroundColor: 'red' }}
              ></Box>
              <Box
                sx={{ height: '30px', width: '150px', backgroundColor: 'grey' }}
              ></Box>
            </Grid>
            <Button onClick={() => setShowMenu('-125px')}>hide</Button>
          </Box>
        </div>
      </div>
    </>
  );
}

Consider creating a custom hook like useToggle for better management of showing/hiding elements. This will streamline your code and make it easier to reuse in other components.

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

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

A guide to creating a synchronous AJAX call using vanilla JavaScript

I am trying to make multiple AJAX calls in a loop using the code below. for (var i = 0; i < 5; i++) { console.log(i); ajax_DatabaseAccessor.query("CheckInt", i, loadQuery); function loadQuery(data) { alert(DWRUtil.toDescriptiveString ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling. Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all ...

React: Resolving the issue of "children" property not found in type "IntrinsicAttributes & Props"

Currently, I am attempting to retrieve data from an API and showcase it in a list of cards using React with TypeScript. As I am relatively new to working with React in Typescript, I am uncertain about how to resolve this error or if I have overlooked somet ...

jQuery sliding tabs

Hello everyone! I am currently on the search for a specific slider, and I'm hoping to find a good example of it similar to what is demonstrated HERE. Unfortunately, I do not know the official name of this particular type of slider, making it challengi ...

JavaScript encounters an error when trying to create a MarkLogic instance with an array

[javascript] XDMP-CAST: (err:FORG0001) xs:string#1(.) -- Invalid cast: `json:object(<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema" ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>) cast as xs:string Stack Tr ...

Tips on incorporating a URL from a text file into a string

Could anyone assist me in adding a URL text file containing just one sentence and saving it as a string? Your help would be greatly appreciated. Thank you. ...

The integration of Tinymce and Vuetify dialog is causing issues where users are unable to input text in the source code editor or add code samples

Having an issue with the Vuetify dialog and TinyMCE editor. Upon opening the dialog with the editor inside, certain functionalities like Edit source code or Insert code sample are not working as intended. Specifically, when attempting to use one of these p ...

What are some strategies I can use to prevent issues with my web design while updating bootstrap?

I recently updated Bootstrap CDN from version 4.0.0 alpha to beta this morning. Here is a snapshot of how the web page looked before (still under construction): Website with Bootstrap 4.0.0 alpha And here is how it appears now: With Bootstrap 4.0.0 bet ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...

Troubles with image uploading on MERN stack with multer are preventing functionality

I am facing an issue while trying to upload an image in MongoDB using multer and React. The problem is that I am unable to post the image successfully. My form consists of three inputs: title, content, and image. When I try to post only the title and conte ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

Struggling to determine if the checkbox has been ticked?

I have integrated a like button on my website using socket io to ensure that it updates for all users when the like button is clicked. I have successfully implemented a like() function that emits liked, increments a counter, and displays it on the page. Ho ...

Can you determine the height of an image if only the width and border width are provided?

Currently delving into the world of HTML and CSS, I've successfully configured the img element's width and border width using a style element. However, one aspect that is still puzzling me is how the height is calculated in this scenario. I&apos ...

When working with React Native, encountering an issue where passing props using the Map function results in an error stating "undefined is not a function" near the section of code involving the

Hey there! I'm currently facing an issue with fetching data from my Sanity CMS and passing it as props to a child component. Interestingly, the same code worked perfectly on another screen, but here I seem to be encountering an error. Although the dat ...

Seeking an efficient localStorage method for easy table modification (HTML page provided)

Currently, I am in the process of developing a custom 'tool' that consists of a main page with a menu and several subpages containing tables. This tool is intended for composing responses using prewritten components with my fellow colleagues at w ...

Error message in console: React Form showing "Form submission canceled due to lack of connection" despite successful submission

I am facing an issue with my form in my React app. Even though the form is successfully submitting data to a list of boxes, I received an error in the console. The error message says: Form submission canceled because the form is not connected In my Rea ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...