Form Style Components

I am currently using a form that contains material-ui components. Instead of relying on inline styles for the width property, I want to use css-in-js instead. I have previous experience with styled-components but there seems to be no form element available through that method.

The only example I found was one where they used pre-built styled component labels. Since I've also implemented validation on these material ui text fields, I want to maintain the structure without changing it. Can someone advise on the best way to apply styles using css-in-js? Ideally, I would prefer a solution involving styled-components.

          return (
            <div className="main-content">
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
            </div>
          );

Answer №1

Here is a simple way to create a styled form:

import styled from 'styled-components';

const StyledForm = styled.form`
   width: 100%;
`;

Now you can use it in your code like this:

    return (
            <div className="main-content">
              <StyledForm
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </StyledForm>
            </div>
          );

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

Styling a list within a div using CSS

I have a CSS file that looks like this: .h_bg{ height:100%; background-size:auto 100%; background-position:center center; background-repeat:no-repeat; position:relative; } .h_bg h1{ width: 100%; position:absolute; line-heig ...

Tablet-friendly dropdown menu

Seeking advice on implementing @media queries for tablets with a width of 991px. Currently, the CSS file is optimized for mobile devices but needs adjustments for tablet responsiveness in the dropdown menu. I attempted the following CSS code: @media (max ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Cross domain tracking pixel implemented using ASP.NET, jQuery, and AJAX technology

Currently, I have a page tracking system that uses $.post(PAIRS-DATA) in JavaScript to send collected information back to the server and load as a tracking pixel. finally { //tracking pixel Response.ContentType = "i ...

Dealing with website links in Next.js and Chakra-UI: Tips and Tricks

When incorporating react linkify directly with chakra-ui components such as Text, the links cannot be managed. Issue Example import Linkify from 'react-linkify'; import {Box, Text} from '@chakra-ui/react'; export default function Usag ...

The 'undefined' type cannot be assigned to the 'never' type

interface A { name?: string age: number } var a: A = { name: '', age: 23 } var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => { if (a[key] || a[key] === 0) { prev[key] = a[key] // an error was reporte ...

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

What is the best way to exclude a particular character from a text element utilizing jquery?

Looking to extract the numerical value from a div containing: <div class="balance"...>$500.48</div> The goal is to retrieve 500.48 as a number, not a string. One approach is to use alert($(".balance").text()) to verify that the content is ret ...

Discovering the magic of drawing on mobile devices using canvas in Javascript

I am having trouble getting this canvas drawing code to work on mobile browsers const canvas = document.getElementById("draw"); canvas.width = window.innerWidth - 60; canvas.height = 400; let context = canvas.getContext("2 ...

Steps for declaring CSS values with fallbacks in case of unsupported values

I'm looking to utilize the overflow: overlay property in Chrome, and overflow: scroll in Firefox. Simply declaring the overlay value causes Firefox not to scroll at all, even though I know it's not standard. My question is: what's the optim ...

Retrieve all user records, excluding the currently logged in user

Having trouble implementing a filter logic in my local meet app similar to Tinder. How can I display all users on the main page except for the user who is currently logged in? I've tried using the filter method but can't seem to get it right. Any ...

Using the theme's primary color instead of selecting a specific color within Material UI

I recently worked on a project using ReactJS and Material UI, where I customized the theme colors. const customTheme = getMuiTheme({ fontFamily: 'Roboto, sans-serif', palette: { primary1Color: cyan500, primary2Color: cyan7 ...

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

Setting up dynamic routes in a Vue.js Express application

I am currently working on a project that involves creating a basic Vue.js Express profile interface. This interface is responsible for retrieving profile information of a specific user based on a unique ID assigned to each user. The .get() request in Vue.j ...

Timer countdown: Looking for a countdown timer that will reset to 3:00 automatically each time it reaches 0 minutes, and can do so

Seeking a continuous countdown timer that starts from 03:00 and counts down to 0:00, then automatically resets back to 03:00, in an infinite loop. The condition is that no one should be able to manually stop this logic. After researching, I found a Ja ...

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...

Using React to retrieve information from a .json file and comparing it against user input

I'm currently working on a Covid dashboard and I would like to incorporate a JSON file into it. However, the way the data is structured within the file is causing me some difficulties. https://i.sstatic.net/PiqCm.png Within the "airport" name field, ...

How can we stop the navigation submenus (ULs) from appearing as if they are floating?

I've created a navigation bar with an unordered list consisting of smaller unordered lists, each with the class "subnav". When the screen is small, the navigation collapses and the menus stack on top of each other. I want the navigation to maintain i ...