Search code examples
htmlcssreactjsantd

How to align upload and input field in the same line?


I am trying to align upload button and a text field which displays the file name in the same line with some gap in between. It's not coming in the same line at all.

This is the code I have written:

<div>

  <Form.Item name='fileupload' getValueFromEvent={e => handleChange(e)} value='file'>
    <Upload maxCount={1} showUploadList={false} beforeUpload={() => false}>
      <Button type='primary' className='upload-button'> Upload </Button>
    </Upload>
  </Form.Item>

  <div style={{float:"right"}}>
    <input className='file-name' style={{height: "40px", width: "400px"}} value={filename}></input>
  </div>

</div>

This is my css file

.upload-button {
  align-items: center;
  gap: 8px;
  width: 150px;
  height: 40px;
  flex: none;
}
.file-name {
  box-sizing: border-box;
  border-radius: 4px;
}

I used antd Space to align it but when I used that getValueFromEvent function never gets called. Form item needs to have only upload button for that function to be called. So, when I do that, the buttons are coming in different lines. What do I add to my code to put them in the same line?


Solution

  • Few modifications you need to make to bring the upload button and the input on the same like,

    Create a parent div as wrapper to the upload button and input box and give display as flexbox for the parent wrapper,

       <div className="input-wrapper">
          <Form.Item
            name="fileupload"
            getValueFromEvent={(e) => handleChange(e)}
            value="file"
          >
            <Upload maxCount={1} showUploadList={false} beforeUpload={() => false}>
              <Button type="primary" className="upload-button">
                {" "}
                Upload{" "}
              </Button>
            </Upload>
          </Form.Item>
    
          <div style={{ float: "right" }}>
            <input
              className="file-name"
              value={filename}
              style={{ height: "40px", width: "400px" }}
            ></input>
          </div>
        </div>
    

    And then make few changes of css like moving gap: 8px to the input-wrapper div and can remove align-items: center and flex: none from the .upload-button and css looks like,

    .input-wrapper {
      display: flex;
      gap: 8px;
    }
    .upload-button {
      width: 150px;
      height: 40px;
    }
    .file-name {
      box-sizing: border-box;
      border-radius: 4px;
    }
    

    Working Example:

    Edit Ant design file upload (forked)

    Also as a note please consider having styles in the css file alone instead of making it inline.