What is the best way to create two fields side by side within a single row?

I'm struggling to merge the data array of two different identity types into one row as a field. Here's the code I've written:

import React from 'react'
import {Form,Field,ErrorMessage,Formik} from 'formik'
import * as yup from 'yup'

const schema=yup.object().shape({
    cmt:yup.string().min(4,'minimum 4 words').required('comment is required'),
    name:yup.string().required('Name is required'),
    email:yup.string().required('Email is required'),
    website:yup.string().required('Enter website URL or name'),
})

function ReplyForm() {
    const data=[
        {type:'text',placeholder:'Write a comment',identity:'cmt'},
        {type:'text',placeholder:'Name',identity:'name'},
        {type:'email',placeholder:'Email',identity:'email'},
        {type:'text',placeholder:'Website',identity:'website'},
    ]
  return (
    <div className='w-full flex justify-center'>
        <div className='w-10/12 bg-blue-200'>
            <Formik
            initialValues={{
                cmt:'',
                name:'',
                email:'',
                website:'',
            }}
            validationSchema={schema}
            onSubmit={(values)=>{
                console.log(values)
            }}
            >
                {({handleSubmit})=>{
                    return <Form onSubmit={handleSubmit}>
                        <div className='w-3/5'>
                            {data.map((val,i)=>{
                                
                                    if ((val.identity==='name')||(val.identity==='email')){
                                       return <div key={i} className='flex justify-between'>
                                            <Field type={val.type} name={val.identity} placeholder={val.placeholder} className='w-1/2'/>
                                        </div>
                                    }
                                    else{
                                        return <div key={i}>
                                        <Field type={val.type} name={val.identity} placeholder={val.placeholder}/>
                                        </div>
                                    }
                            })}
                        </div>
                    </Form>
                }}
            </Formik>
            
        </div>

    </div>
  )
}

export default ReplyForm

The current output looks like this: https://i.sstatic.net/KIIpO.png

However, my desired outcome is to have the "name" and "email" fields on the same row, similar to this: https://i.sstatic.net/3lM3K.png

Please assist me in achieving this layout.

Answer №1

Flex works differently in this scenario. To align the name and email in a row, you need to wrap them inside a flex container. I suggest setting the parent node to have flex-wrap property while the children nodes have a width of 100%. For the name and email, set their width to 50% each (adjust if there are gaps by using calc or other methods). Here's an example:

.container{
  width: 200px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 20px;
}
.item{
  width: 100%;
  background: #afc;
  height: 50px;
}
.item:nth-child(2),
.item:nth-child(3){
  width: calc(50% - 20px);
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Answer №2

It's recommended to utilize CSS Grid.

Sample Code:

<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 p-20">
    <div class="sm:col-span-2">
        <div class="w-full h-28 bg-red-500 rounded-md text-white text-2xl text-center p-10 font-mono">Large 1</div>
    </div>
    <div>
        <div class="w-full h-14 bg-red-500 rounded-md text-white text-2xl text-center p-3 font-mono">Half</div>
    </div>
    <div>
        <div class="w-full h-14 bg-red-500 rounded-md text-white text-2xl text-center p-3 font-mono">Half</div>
    </div>
    <div class="sm:col-span-2">
        <div class="w-full h-14 bg-red-500 rounded-md text-white text-2xl text-center p-3 font-mono">Middle</div>
    </div>
</div>

Output:

Description:

grid is used to set up the grid. Use grid-cols-1 to form a grid with 1 equally sized column for mobile devices.

Apply gap-6 to adjust the spacing between rows and columns in the grid. sm:grid-cols-2 creates a grid with 2 equally sized columns for screens wider than 640px.

To align elements on the same line (e.g., "comment" and "website"), use sm:col-span-2 to make them take up the entire horizontal space on screens wider than 640px.

Check out the sandbox.

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

Spinning Earth orbits around the Sun

My goal is to create a 3D Solar system, starting with the Sun and Earth using THREE.SphereGeometry() var sphere2 = new THREE.Mesh(new THREE.SphereGeometry(50, 100, 100), new THREE.MeshBasicMaterial({side: THREE.DoubleSide, map:txt2})); sphere2.position.se ...

How can I retrieve information from an HTML or JavaScript object?

Imagine a scenario where you have an HTML table consisting of 5,000 rows and 50 columns, all generated from a JavaScript object. Now, suppose you want to send 50 checked rows (checkbox) from the client to the server using HTTP in JSON format. The question ...

Prevent scrolling on both md-sidenav and md-content in AngularJS Material

Currently, I am working on a website using AngularJs Material sidenav. My goal is to make both md-sidenav and md-content appear as one page, without any scroll bars showing up when the height of one element exceeds that of the other. How can I achieve th ...

Styling the <div> element to create a unique rotation and tilt aesthetic

Would anyone be able to guide me on how to recreate the tilted style of the header section shown in the image using HTML and CSS? https://i.sstatic.net/mhJWA.png body { margin: 0px; background-color: #FFEF4C; } #header { background-color: #FF35 ...

Leveraging CSS nth-child selector in conjunction with ngFor in angular2

Looking for a way to style odd and even rows differently in my dynamically generated table using ngFor directive in angular2. *ngIf="AreThereMyOldMessages" *ngFor="let oldm of MyOldMessages;let i=index" *ngIf="AreThereMyNe ...

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

Designing Forms with Label Placement above Input Fields

I am working on creating a form with the following layout: <form name="message" method="post"> <section> <label for="name">Name</label> <input id="name" type="text" value="" name="name"> <label for="email"& ...

Is there a way to extract all the content from a webpage's body using BeautifulSoup?

Looking to extract text from a medical document webpage for a Natural Language Processing project using BeautifulSoup, but encountering challenges. The specific website in question is located here: The goal is to capture the entire text body by utilizing ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

AngularJS enables seamless two-way data binding with DropDownList in the Model-View-Controller (M

As a beginner in AngularJS, I am currently experimenting with implementing 2-way data binding for the Gender Dropdown menu similar to what I have done with textboxes. Below is a snippet of code for the dropdown control: <div class="form-group"> ...

How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Accessing nested arrays and objects within JSON using Node.js

I'm in the process of developing an application that retrieves a JSON response from an API call using SONARQUBE. With node js, how can I extract the value of duplicated_lines from the following JSON object? I attempted the code below but it always r ...

Unlock the Power of Angular: Leveraging ViewEncapsulation.Native to Access HTML Elements

I am encountering an issue where I am receiving an error when trying to access an HTML element by ID. The problem arises when I attempt to access the classList upon a user clicking a button to apply a different style class to the element. The class list an ...

The results from various <div> elements are displayed based on the selection made from the dropdown menu

<body> <label for="country">Country : </label> <select id="country"> <option>Please select</option> <option name="CountryRevenue">Revenue</option> <option name="CountryQuantity">Quantity ...

React JS FormControl not functioning properly to toggle checkbox within a modal window

Upon editing a specific resource, a modal pops up to record the changes and update the application. Extracted from the homepage rfc const [flags,setFlags] = React.useState({}) . . . flags[object1]={flag1: true, flag2:false}; flags[object2]={flag1: true, f ...

Enhance Your React App with Material UI Textfield Featuring Thousands Separator

I need help styling my text field to display numbers with a $ sign and thousands separators, like $120,000 instead of 120000. I am encountering two warnings: 1.) Warning: Failed prop type: The prop name is marked as required in ForwardRef(NumericFormatCus ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

The custom CSS I have created does not take precedence over the Bootstrap CSS

I'm struggling to understand why my custom CSS file isn't able to override the Bootstrap CSS. I know that my new CSS class should have higher priority than Bootstrap's, but for some reason, it's not working as expected. Here's the ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to ...