Tips for including a permanent button at the bottom of a material ui dialog box

I want to implement a dialog popup in my react js application. When the user clicks on a button, the dialog should open up. Inside the dialog, there is a form with input fields. After the user fills out all the inputs, they can submit the information by clicking the "submit" button at the bottom of the dialog. However, I am facing an issue where the submit button is not sticking to the footer. Even if there are more than 15 inputs, the user has to scroll all the way down to see the "submit" button. I am aware that material ui provides DialogActions for this purpose, but since the dialog is in the parent component, I cannot access DialogActions from the child component. Here is my code:


App.js (parent)

import React, { useState } from "react";

import Info from "./Info";
import Dialog from "@material-ui/core/Dialog";
import { DialogTitle } from "@material-ui/core";

import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";

import { DialogActions } from "@material-ui/core";

export default function App() {
  const [open, setOpen] = useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={handleClickOpen}>Click me to open dialog</button>
      <Dialog
        open={open}
        aria-labelledby="responsive-dialog-title"
        maxWidth="md"
        setMaxWidth="md"
        fullWidth={true}
      >
        <dialogContent>
          <dialogTitle>
            {" "}
            <div>
              <h4>Fill out the form</h4>
            </div>
          </dialogTitle>
          <DialogContentText>
            <Info />
          </DialogContentText>
        </dialogContent>
        {/* <DialogActions>
          <button id="responsive-dialog-title" onClick={handleClose}>
            {" "}
            Submit{" "}
          </button>
        </DialogActions> */}
      </Dialog>{" "}
    </div>
  );
}

and Info.js (child) :

import React, { useState } from "react";

export default function Info() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleSubmit = () => {
    console.log(username);
    console.log(password);
    console.log(address);
  };
  return (
    <form onSubmit={handleSubmit}>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          width: "350px",
          padding: "20px"
        }}
      >
        <label> Username</label>
        <input
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          type="text"
        />
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          width: "350px",
          padding: "20px"
        }}
      >
        <label> Password</label>
        <input
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          type="password"
        />
      </div>

      <button> Submit</button>
    </form>
  );
}

codesandbox

Can anyone suggest a way to ensure that the "submit" button in Info.js is fixed at the bottom or displayed using DialogActions? Any help would be appreciated.

Answer №1

To achieve this effect, use the CSS property position: fixed. Here is an example of how your code would look:

<form onSubmit={handleSubmit}>
  <div>
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        width: "350px",
        padding: "20px"
      }}
    >
      <label> Username</label>
      <input
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        type="text"
      />
    </div>
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        width: "350px",
        padding: "20px"
      }}
    >
      <label> Password</label>
      <input
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        type="password"
      />
    </div>
  </div>
  <div style={{ position: "fixed" }}>
    <button> Submit</button>
    <button> Cancel</button>
  </div>
</form>

To remove the default scroll from the dialog, you can do the following:

<Dialog
    open={open}
    aria-labelledby="responsive-dialog-title"
    maxWidth="md"
    setMaxWidth="md"
    fullWidth={true}
  >
    <div style={{ overflow: "hidden", height: "100%", width: "100%" }}>
      <dialogTitle>
        {" "}
        <div>
          <h4>Fill out the form</h4>
        </div>
      </dialogTitle>
      <Info />
    </div>
  </Dialog>

This approach works, but it's recommended to call the submit function from the parent component. The inputs can be populated using context or a simple state in the parent.

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

False return - Inoperative link - Scroll option

I have a JavaScript drop-down menu that is functioning correctly, but when I click on one of the links in the dropdown, the link does not work. I suspect it has something to do with my "return false/true" setup. Here's my JavaScript code: function d ...

What is the best way to control the iteration of a JavaScript 'for' loop based on specific conditions?

I need help with controlling the iteration of a 'for' loop in Javascript. Here is the code snippet: for (var j=0; j < number; j++){ $('#question').empty; $('#question').append('' + operand1[j], operator[j ...

If the text width of a label exceeds the total width of its container, intelligently display a sub-string based on pixel calculations

I am looking to shorten the text inside a label if its width exceeds the total width of its container. Instead of displaying the full text, I want to display a sub-string of it. if (SensorType.Text.Length >= 25) { SensorType.Text = SensorType.Text ...

What is the method to access nested JSON data returned from the Angular JS $http service?

Here is the main JSON file I am using { "chartType" : ["column", "column", "pie"], "chartTitle": ["Number of teams", "Number of consumable items","Number of employees in charge"], "yAxisTitle": ["Teams", "Consumables", "Employees"], "seriesName": ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

The browser does not automatically set the Cookie

Trying to login involves making an API call using a POST HTTP request. post( postLogin(email), JSON.stringify({password: passwd}), { headers: { "Content-Type":"application/json" }, credentials: 'include' // also attempted with &a ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Deploying a node add-on to a server bypassing the use of localhost

Currently, I have developed a node application that runs successfully on my local server. The project consists of an index.html file located in a public directory, along with the main app.js file. By executing the command node app.js in the terminal, the a ...

The "Go" button on iPhone triggers an error before the page is sent back

I am facing an issue with a web page that has a form containing multiple submit buttons with different functionalities like clearing the form, performing a calculation, or adding another entry line. The problem arises only on iPhone devices (tested on bot ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

I was able to resolve the fixed position issue of a button on Safari for iPhone 3G

Here is the setup I have on jsfiddle: http://jsfiddle.net/zZDqH/ Currently, there is a button fixed at bottom:0px. You can scroll up and down the page, and the button will stay at the bottom of the page. However, when testing in Safari on an iPhone 3G ( ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

Tips for utilizing flexbox and React-Native to ensure a cropped image takes up the entire View

I'm trying to create a cropped image that fills the entire screen in my app. Currently, my code looks like this: https://i.stack.imgur.com/9DtAc.png However, I want the small square of Homer eating donuts to occupy the entire screen, similar to the ...

Inconsistent alignment and formatting of fields in Bootstrap jQuery form

I need assistance with creating a form that includes three input fields: first name, last name, and email. Additionally, I would like to provide users with the option to add more groups of input fields. Currently, the three fields and the button are displ ...

Material UI grid with 2 items: one aligned to the left and one aligned to the right in a single line

I'm struggling to understand how to effectively utilize Material UI's flexbox integration. I want to align items in a specific way, like this: export default function Home() { return ( <Grid container justify={"space-between&q ...

Incorporating TinyMCE into numerous dynamically generated text areas

I am facing an issue with dynamically created textareas. The content in these textareas is generated dynamically. This is how I retrieve the data and create the textareas dynamically: $(document).ready(function(){ $('#btn').click(function(){ ...

Can one recover a Javascript file from a server?

In Python, I am able to extract Javascript code from an HTML file using the code snippet below. import urllib2, jsbeautifier from bs4 import BeautifulSoup f = urllib2.urlopen("http://www.google.com.ph/") soup = BeautifulSoup(f, "lxml") script_raw = str( ...

Remove outdated choices from subcategory menu upon JSON data retrieval

By using the onchange event in the parent dropdown (first dropdown), I am populating the child dropdown (second dropdown). Subsequently, upon selecting an option from the child dropdown, I automatically fill in three text boxes. However, I am facing an iss ...

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...