What is the best way to align the checkbox and label in a React form?

I've been struggling to align the labels next to the checkboxes on this form. I'm currently utilizing React with React-Hook-Form for validation and state management (you can find the code on GitHub: https://github.com/cipdv/ciprmt-mern/blob/main/client/src/components/User/HHForm/RFHHHForm.js - the file containing the form is RFHHHForm.js).

I have attempted a few solutions:

  1. I tried using Semantic UI's library in this way:
<div className='inline field'>
                    <div className='ui checkbox'>
                        <input defaultChecked={healthHistory?.epilepsy} name="epilepsy" type="checkbox" id="epilepsy" {...register('epilepsy')} />
                        <label>Epilepsy</label>
                    </div>
                    <div className='ui checkbox'>
                        <input defaultChecked={healthHistory?.diabetes} name="diabetes" type="checkbox" id="diabetes" {...register('diabetes')} />
                        <label>Diabetes</label>
                    </div>

Although this method aligned the labels and checkboxes, the checkboxes were no longer editable (unable to be checked or unchecked).

Another attempt involved creating a custom CSS stylesheet module like so:

input[type="checkbox"]
{
    vertical-align:middle;
}

label,input{
    display: inline-block;
    vertical-align: middle;
}

However, this approach did not successfully align the elements as intended.

Answer №1

One possible solution is to enclose the input within a label element

<label>Diabetes &nbsp; <input defaultChecked={healthHistory?.diabetes} name="diabetes" type="checkbox" id="diabetes" {...register('diabetes')} /></label> 

Alternatively, you can use your checkbox class like this:

.checkbox{
  display: flex;
  align-items: center;
}

Please inform me if this resolves the issue.

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

The custom autocomplete feature doesn't pop up in a dialog as shown in the example

I've encountered an issue with a custom autocomplete feature within a dialog where the autocomplete won't open as expected. To see this problem in action, check out the code sandbox link provided below. Within the sandbox, you'll find: A ...

Best practices for managing an array of buttons and handling click events in ReactJs

While working on my react class component, I encountered an issue. The alert popup keeps appearing constantly without any button click as soon as the component renders. onHandleOnClick(data, e) { console.log(data); alert("got it" + data); } rend ...

Looping through required fields in jQuery based on a CSS class

Is there a way to loop through required fields marked with <input class="required">? Currently, only the first input in the loop is being evaluated. How can I traverse the DOM using a loop to check all input boxes? Thank you for your help. While I ...

managing a multitude of socket.io events within my ReactJS application

My ReactJS app is integrated with socket.io, but I am facing an issue where too many socket events are causing my app to render multiple times in less than a minute. This eventually leads to freezing of the app. I am looking for the best way to handle this ...

Encountering a problem with MongoDB when trying to import a JSON file

I'm struggling to import my JSON file into MongoDB. Even though I don't see any errors like "missing { symbol," MongoDB keeps throwing an error at me. What should I do to fix this issue? I tried following a sample and made edits accordingly, but ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

`Implementing Moovweb React Storefront on an Express Server`

Start on the official Documentation server by running: npm run start:express Or yarn start:express For documentation, visit: Error Log exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; ^ Typ ...

Disabling the ability to edit the rightmost portion of an input number field

I am looking for something similar to this: https://i.stack.imgur.com/ZMoNf.jpg In this case, the % sign will be shown in the input field by default and cannot be changed or removed. The user is only able to modify the number to the left of the % sign. P ...

Removing a section of HTML from an EmailMessage Body in EWS

Is there a way to remove certain parts of the EWS EmailMessage .Body.Text value in C# before replying with a ResponseMessage? The elements that need to be removed include clickable and non-clickable buttons in HTML format. Since custom tags cannot be dec ...

Utilizing CSS Grid to dynamically stretch and wrap rows based on adjacent siblings within a flat DOM structure

Looking for a way to create a grid layout that adjusts row sizes based on adjacent siblings. Interested in SCSS or CSS solutions using grid, flexbox, or other techniques. https://i.sstatic.net/Ump5U.png I am working with a dynamically generated list base ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

Issue: The "props" method is designed to be executed on a single node, but it was found on 2 nodes instead

it('should execute setCampaignDate when clicked', function () { let spySetCampaign = sinon.spy(wrapper.instance(), 'setCampaignDate'); let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker); a ...

Showing Firestore Data as a map type: Issue encountered - React child cannot be an Object

Retrieving data from firestore: const [product, setProduct] = useState([]); const fetchProducts = async () => { const querySnapshot = await getDocs(collection(db, "products")); const productsArray = []; querySnapshot.forEach((doc) => { ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

Issues with cookies are preventing functionality when accessing a developmental version of a Next application on a mobile device

During testing of my Next JS development build on a mobile phone, I accessed it using a private IP address (192.XXX.X.24:3000) rather than localhost:3000 on my development machine. The pages load correctly, but when attempting to send cookies back to the b ...

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

HTML min-width is not being considered by the media query breakpoint

After resizing the browser window to less than 480px, my site reverts back to its original style (the css not defined inside the mixins). I attempted to limit the html with min-width, but despite the browser displaying a horizontal scrollbar, the css still ...

Animating two elements on scroll at specific point with speed problem

Trying to create an animation with two different images once a user reaches a specific point on the page. The animation works, but there is an issue when using a trackpad - the movement appears slow compared to scrolling with a mouse. I've already att ...

What is the best way to align a button within a Jumbotron?

Struggling to find the right CSS placement for a button within a jumbotron. I attempted using classes like text-left or pull-left, but nothing seemed to work as I hoped. I believe a simple CSS solution exists, but it's eluding me at the moment. Ideall ...