Is it possible to adjust the height of a div based on different conditions

I'm currently working on a React project where I need to conditionally display a div above an existing one that covers the screen with an image. My goal is to have the existing div shrink in height, reducing the size of the image when the second div is displayed. The height of the second div may vary, such as when displaying a list of items.

Here's a simplified version of my current setup in the App:

function App() {
  const [show, setShow] = useState(false);
  return (
    <div
      style={{
        border: "solid",
        width: "100%",
        maxHeight: "100vh"
      }}
    >
      {show && (
        <div>
          <div style={{ height: "300px", backgroundColor: "red" }}></div>
          <button
            onClick={() => {
              setShow(false);
            }}
          >
            Close
          </button>
        </div>
      )}
      <div
        style={{
          display: "flex",
          justifyContent: "center"
        }}
      >
        <img
          src="https://i.imgur.com/LiAUjYw.png"
          alt="test"
          style={{
            maxWidth: "100%",
            height: "auto"
          }}
        />
      </div>
      <button onClick={() => setShow(true)}>SHow</button>
    </div>
  );
}

Originally, it appears like this: https://i.sstatic.net/GrD8C.jpg

Then, upon clicking the 'Show' button, it changes to this: https://i.sstatic.net/4S6ic.jpg

You can observe that the bottom div shifts down and extends beyond the container div.

I'm seeking advice on how to create responsive styling so that the div adjusts its height when the other element is rendered. Any suggestions or assistance would be greatly appreciated.

Thank you.

Answer №1

Consider this straightforward concept. Look at how the divs are styled in this manner:

<div
    style={{
        display: "flex",
        justifyContent: "center"
    }}
>

Observe the peculiar {{ }} notation used for the style. This is because the style requires an object, and the object specified is:

{
    display: "flex",
    justifyContent: "center"
}

You can assign that object to a variable somewhere, such as:

const styleWhenShow = {
    display: "flex",
    justifyContent: "center",
    height: "100px"
}

const styleWhenNoShow = {
    display: "flex",
    justifyContent: "center",
    height: "500px"
}

With your existing show state, you can simply replace the style prop with:

style={show ? styleWhenShow : styleWhenNoShow}

If you wish to avoid repeating common styles between showing and not showing, you could try something like this:

const commonStyle = {
    display: "flex",
    justifyContent: "center"
}

const styleWhenShow = {
    height: "100px"
}

const styleWhenNoShow = {
    height: "500px"
}

Then set the style prop as follows:

style={show ? { ...commonStyle, ...styleWhenShow } : { ...commonStyle, ...styleWhenNoShow }}

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

When clicking on a link in React, initiate the download of a text file

Usually, I can use the following line to initiate the download of files: <a href={require("../path/to/file.pdf")} download="myFile">Download file</a> However, when dealing with plain text files like a .txt file, clicking on ...

Gradually eliminate the background color in one smooth motion

When new messages appear, I want them to be subtly highlighted as users hover over them. The background color will slowly disappear on hover thanks to the CSS code provided below. However, this effect should only happen once, which is why I need to remov ...

Encountering the "Expression Expected" error while attempting to execute a test with CreateRemixStub and Vitest

Whenever I initiate the test by running "npx vitest", I encounter the following: https://i.sstatic.net/TpM2oyYJ.png My application is a Shopify Hydrogen v2 built on top of Remix Run. I aim to set up a test for the AddToFavoritesButton component to verify ...

npm encountered a premature closure

I recently purchased and started using a ReactJS template which you can check out here My goal is to install all the dependencies by running npm install in the root directory of the template (React-App) However, I encountered an ERROR message like this: ...

Understanding the concept of margins and managing tile layouts

I'm facing a few issues that I can't seem to resolve, and I would appreciate some guidance on how it all works. Firstly, I have a container with the ID "kafle" which I've positioned as desired, but now I want to add multiple tiles into it. M ...

How can I create boxes that expand when hovered over?

I am currently exploring ways to create a hover effect where divs or boxes open and animate downward when hovered over. I checked the Bootstrap documentation but couldn't find a built-in solution. Considering using JavaScript, but my knowledge in that ...

Make sure to pass refs when using FC children with Next.js Links

I am struggling to understand the documentation in next.js regarding passing refs to children functional components. It's confusing to me and I'm finding it difficult to implement. For example, let's consider a functional component that dis ...

What causes a merge conflict to occur within a React and Typescript project?

I stumbled upon this code snippet in our React/Typescript - JSX/TSX project with an unresolved Git merge conflict. Interestingly, the code successfully compiles and runs in the browser! Upon transpilation, I noticed that the top element is recognized as t ...

Formio UI is experiencing issues with its display when rendered alongside ReactDOM

Recently diving into the world of React and getting the hang of hooks, I've encountered a challenge with getting the Formio plugin to cooperate with a component. Uncertain about how to implement React.DOM with hooks, the Formio documentation suggests ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Unable to make API calls in test files when using Create React App and Jest

I am encountering an issue with calling an API in a test case for a create-react-app that I have created. The API call is being made successfully, however, nothing seems to be executed within the .then function. The reason why this is problematic for me i ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

I'm curious, what's your strategy for handling the Gutenberg block previews in the backend?

Is there a way to customize Gutenberg block previews in the WordPress admin area? For instance: If I create a block using Bootstrap and my own custom CSS, will WordPress load Bootstrap and my CSS to show a preview in the admin area? ...

Using Function Call to Generate Components in React

Being tired of repeatedly defining states to render Components based on conditions, I often find myself just wanting to display notifications or alerts. My current dilemma is figuring out how to render a component by invoking a function from within that co ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

What steps can I take to avoid Vue.js overriding jQuery bindings within components?

After incorporating vue.js into an existing project and attaching the vue instance to the body tag with an ID of "app," everything seemed to be running smoothly. jQuery and Vue.js were cooperating well together. However, as soon as I started creating compo ...

Why is it not possible for me to change the font color to white?

To modify the font of the accordion heading to white, please check out the screenshot provided below. While the code functions properly in "fiddle", it seems that when I inserted the CSS snippet into a SharePoint 2013 page, the font color does not display ...

Having trouble with Vue and Vuex not returning the correct value in HTML?

I've implemented a navbar that displays specific menu items based on the user's role. Below is the simplified HTML code for the navbar: <v-speed-dial class="speed-dial-container contextual-text-menu" v-if="user && user. ...