Sizing Children in Ant Design Inline Forms

I'm having trouble making my form inline with a select taking up 60% of the space and a submit button taking up the remaining 40%. Every time I try to do this, the select and button end up sizing themselves incorrectly. The select starts out very small and the button ends up smaller than its text. What should I do in this situation?

<Form layout="inline">
    <Form.Item style={{width:'60%'}}>
        {getFieldDecorator('studentId', {
            rules: [{ required: true, message: 'You must select a student' }],
        })(
            <Select style={{width:'100%'}}>
                {this.props.linkedStudents.map(x => <Select.Option value={x.id}>{x.fullName}</Select.Option>)}
            </Select>
        )}
    </Form.Item>
    <Form.Item style={{width:'30%'}}>
    <Button
        type="primary"
        htmlType="submit"
        style={{ width: '30%' }}
    >
        Remove from Team
    </Button>
    </Form.Item>
</Form>

Answer №1

To customize the appearance of the ant-form-item-control-wrapper, you have two options: use CSS directly or modify the wrapperCol property of the Form.Item.

In order for the following code snippet to take effect, ensure that the Select component within the Form.Item is enclosed within an element with the class select-container:

.select-container.ant-form-item-control-wrapper {
  width: 100%;
}

Alternatively, you can achieve the same result by using the following code:

<Form.Item wrapperCol={{ sm: 24 }} style={{ width: "60%", marginRight: 0 }}>

The sm attribute corresponds to the column layout, while the value 24 refers to the outline of the column.

For a live demonstration, you can visit the following link: https://codesandbox.io/s/w0voxxxzm5 (assuming you prefer no gap between the select component and the button).

components/InlineForm.js

import React, { PureComponent } from "react";
import { Button, Form, Select } from "antd";
const { Item } = Form;
const { Option } = Select;

const students = [
  {
    id: 1,
    fullName: "Bob Smith"
  },
  {
    id: 2,
    fullName: "Amber Johnson"
  }
];

class InlineForm extends PureComponent {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        alert(JSON.stringify(values, null, 4));
      }
    });
  };

  render = () => {
    const { getFieldDecorator } = this.props.form;

    return (
      <Form onSubmit={this.handleSubmit} layout="inline">
        <Item
          wrapperCol={{ sm: 24 }}
          style={{ width: "60%", height: 60, marginBottom: 0, marginRight: 0 }}
        >
          {getFieldDecorator("studentId", {
            rules: [{ required: true, message: "You must select a student" }]
          })(
            <Select style={{ width: "100%" }}>
              {students.map(({ id, fullName }) => (
                <Option key={fullName} value={id}>
                  {fullName}
                </Option>
              ))}
            </Select>
          )}
        </Item>
        <Item wrapperCol={{ sm: 24 }} style={{ width: "40%", marginRight: 0 }}>
          <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
            Register
          </Button>
        </Item>
      </Form>
    );
  };
}

export default Form.create({ name: "inline-form" })(InlineForm);

Answer №2

I found that using

style = {{width: "60%"}}
initially worked for me, but ultimately I decided to go with style = {{flex: 1}} instead. This was because I needed to divide the <InlineForm/> into 3 fields.

Check out the simplified hooks version for more details:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Button, Form, Select } from "antd";

const students = [
  { id: 1, fullName: "Bob Smith" },
  { id: 2, fullName: "Amber Johnson" }
];

const InlineForm = () => {
  function handleSubmit(e) {
    e.preventDefault();
  }

  return (
    <Form onSubmit={handleSubmit} layout="inline">
      <Form.Item style={{ width: "60%", height: 90, margin: 0 }}>
        <Select style={{ width: "100%" }}>
          {students.map((student) => (
            <Select.Option key={student.id} value={student.id}>
              {student.fullName}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item style={{ width: "40%", marginRight: 0 }}>
        <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
          Register
        </Button>
      </Form.Item>
    </Form>
  );
};

const App = () => (
  <div>
    App using InlineForm
    <br />
    <InlineForm />
  </div>
);

ReactDOM.render(<App />, document.getElementById("container"));

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

Whenever I find myself being redirected to the login page, my goal is to eliminate the bottomTab from view

I'm looking to eliminate the bottom tab when I land on the login page, even though I've set it up for all pages. However, whenever I click on the login button, the tab remains visible. Here is my current code: import React, { useContext } from & ...

Tips for eliminating the border from a Bootstrap dropdown menu in the navigation bar

I am utilizing the Bootstrap 5 navigation bar and trying to figure out how to remove the blue border from the "Dropdown" when clicked on. Despite my efforts to find a solution, I have been unsuccessful. <nav class="navbar navbar-expand-lg navbar ...

Add extra space to the dimensions of the div by incorporating padding

Showing my issue with an accompanying image: I am looking for a solution to include padding in the width: 50%; calculation. Currently, the first div's width is actually 50% + 2em because the padding was not factored in initially. Is there a way to i ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Smoothly scroll through divs using JQuery

Let me share an issue I'm facing. I have implemented smoothDivScrolling on my webpage. The problem is that the scrollable area containing all the items to be scrolled always ends up being larger than the actual content. When I reach the last item i ...

Troubleshooting problem: Scrolling problem in IE7 and IE8 with Lightbox

The lightbox I'm using works flawlessly on all browsers, except for IE. When viewed on IE, it shows triple scroll bars. Here is the CSS code for the iframe: #wrap { float:left; width:800px; height:500px; overflow-x: hidden; overflow-y: scroll; } #co ...

Creating a CSS grid layout with a scrollbar positioned on the left side and content filling from left to right

How can I move the scrollbar to the left while keeping ng-repeat population from left to right? I'm using an ng-repeat to fill a grid that is 3 by X (Width by height). By default, the scroll bar appears on the right side. I want to position it on the ...

Struggling to successfully deploy a React-Express application on Heroku platform

Attempting to deploy my MERN app (created with create react app) to Heroku has resulted in a recurring 404 error when trying to access the app URL. After reviewing the Heroku error log, the following errors were identified: app[web.1]: ls: cannot access & ...

How to trigger a function to run only once in React when the page is accessed or refreshed

I'm currently developing a search feature using Algolia search functionality. Users can input a search term from another site, be redirected to the search page, and have the search executed automatically. Once on the search page, users must utilize t ...

What's the reason for the element not inheriting margins from its parent?

I am facing an issue with centering an h1 header within a .banner element. When I try to apply margin to the header, it appears to indent not from the top border of the banner, but rather from the nav element located above the banner. After inspecting the ...

What is the procedure for modifying the state array?

I am currently working with a state in my component set up like this: constructor(props){ super(props) this.state={ editableComparatorIndexes: [] } } But I am facing challenges when it comes to updating the state, and I need to achieve som ...

Determining Density Changes in Material-UI's DataGrid/XGrid: A Comprehensive Guide

Is there a more efficient way to adjust the size of the action icon based on table density in response to user interaction? Currently, I am using onStageChange to track all changes in the table and update a state variable on the component. ... ...

Attempting to convert the code from react documentation into class components within a react-create-app, but encountering unexpected behavior

Hey there! I'm currently diving into the world of React and challenging myself by rewriting all the code samples from the documentation in a local react-create-app. However, I've hit a roadblock with this section on the Doc, you can find the code ...

Is there an issue with updating state in React using context?

I am looking to utilize context and usehook within the UploadButton component so that I can access the state in the UserButton component. What I am attempting to achieve? When the button in UploadButton is clicked, the state isDialogOpen is set to true. I ...

The background color of the div or section is stubbornly refusing to change, no matter how much I tweak it

.forBackground { background-color: white; } .kontaktUndMapContainer { width: 100%; padding: 20px; color: gray; text-align: center; } .überschriftKontakt { margin-bottom: 20px; } .überschriftKontakt2 { margin-top: 20px; margin-bottom: 2 ...

Setting a loading status while loading events with FullCalendar React

Currently in my React application, I am incorporating FullCalendar.io for its functionality. However, I have noticed that the documentation is rather limited and not specific to React when it comes to implementing a Loading status. For more information, yo ...

<JavaScript> changing the color of hyperlink in d3.js - <Organizational Chart>

screenshot The width of the link can be adjusted, but the color remains unchanged. I have attempted various solutions series.links.template.setAll({ strokeWidth: 2, strokeOpacity: 0.5, color: am5.color('#ffffff'), links: ...

Oops! TS2307 error: React module not found!

While attempting to build a component using TypeScript, I encountered an error in the terminal stating that it could not find the 'react' module. However, I have already installed both react and react-dom via npm. ERROR in ./main.tsx error TS23 ...

CSS styles do not apply to PDF files when downloading

My table headers are styled with writing-mode: vertical-lr, and they look perfect on the screen. https://i.sstatic.net/cQ6Vm.jpg However, when I used the same CSS to style the PDF file, the headers did not display vertically. It seems like the PDF file d ...

Looking for assistance in developing a button component that, when activated, can smoothly scroll to the next section on the page with

I designed a versatile section component that accepts various props such as a heading, copy, and more. Additionally, I included a child button component that is intended to progress the user to the next heading when clicked. The desired functionality is fo ...