Find a solution to splitting the area in half, with one side designated for the icon and the other for text

https://i.sstatic.net/Ov3yF.png

I'm currently working on a code to assign tasks to employees, and I have created a login form with multiple text fields, each accompanied by an icon. However, there seems to be a layout issue as shown in the image. There is a distinct gap between the input field and the corresponding icon in each section.

As seen in the picture, there's a blue area where the user should input data, while the space designated for the icon remains empty.

How can I resolve this spacing problem?

code.tsx:

const LoginFirebase: FC = (props) => {
  const isMountedRef = useIsMountedRef();
  const { user, loginUserWithEmailAndPassword, loginError } = useAuthModule(
    (state) => state
  );
  console.log('this is the user from the state 1 from Reg-Com: ', user);
  const navigation = useNavigate();
  useEffect(() => {
    if (user) {
      console.log('logged in user: ', user);
      navigation('/dashboard');
    }
  }, [user]);

  return (
    <>
      <Box
        sx={{
          alignItems: 'center',
          display: 'flex',
        }}
      ></Box>
      <Formik
        initialValues={{
          email: '',
          password: '',
          submit: null,
        }}
        validationSchema={Yup.object().shape({
          email: Yup.string()
            .email('Must be a valid email')
            .max(255)
            .required('Email is required'),
          password: Yup.string().max(255).required('Password is required'),
        })}
        onSubmit={async (
          values,
          { setErrors, setStatus, setSubmitting }
        ): Promise<void> => {
          try {
            await loginUserWithEmailAndPassword(values);

            if (isMountedRef.current) {
              setStatus({ success: true });
              setSubmitting(false);
            }
          } catch (err) {
            console.error(err);
            if (isMountedRef.current) {
              setStatus({ success: false });
              setErrors({ submit: err.message });
              setSubmitting(false);
            }
          }
        }}
      >
        {({
          errors,
          handleBlur,
          handleChange,
          handleSubmit,
          isSubmitting,
          touched,
          values,
        }): JSX.Element => (
          <form noValidate onSubmit={handleSubmit}>
            <TextField
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <DraftsOutlinedIcon />
                  </InputAdornment>
                ),
              }}
              error={Boolean(touched.email && errors.email)}
              helperText={touched.email && errors.email}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.email}
              placeholder="Enter your email"
              fullWidth
              margin="normal"
              name="email"
              type="email"
              variant="outlined"
            />
            <TextField
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <LockOutlinedIcon />
                  </InputAdornment>
                ),
              }}
              placeholder="Enter password"
              error={Boolean(touched.password && errors.password)}
              helperText={touched.password && errors.password}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.password}
              fullWidth
              margin="normal"
              name="password"
              type="password"
              variant="outlined"
            />
            {errors.submit && (
              <Box sx={{ mt: 3 }}>
                <FormHelperText error>{errors.submit}</FormHelperText>
              </Box>
            )}
            <Box sx={{ mt: 2 }}>
              <Button
                style={{
                  marginTop: '1rem',
                  maxHeight: '3.4rem',
                  minHeight: '3.4rem',
                }}
                color="primary"
                disabled={isSubmitting}
                fullWidth
                size="large"
                type="submit"
                variant="contained"
              >
                Log in
              </Button>
            </Box>
            {loginError && <p>{loginError}</p>}
          </form>
        )}
      </Formik>
    </>
  );
};

export default LoginFirebase;

Answer №1

Issue

The Textfield seems to be a parent flex div containing two child flex div elements: one for the icon and one for the input. The problem is that the light-blue background is only showing on the child input field when it's focused, which doesn't apply to the parent div.

Resolution

To tackle this issue, you can utilize the :focus-within CSS property. This will enable the parent div to change its CSS styling when one of its child elements gets focused.

Live Example

https://codesandbox.io/s/custom-input-component-5bboy?fontsize=14&hidenavigation=1&theme=dark

Alternative Approach

Another strategy could involve removing the use of flex and instead allowing the input to fill the entire field while positioning the icon over it using absolute position:

https://codesandbox.io/s/custom-input-component-input-as-entire-field-xgbhe?fontsize=14&hidenavigation=1&theme=dark

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

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Navigating a SwipeableDrawer in React with scrolling functionality

I'm currently using a swipeable drawer in React from MUI to display lengthy content. My goal is to keep the title visible even when the drawer is closed, and I was able to achieve this through the following method: MUI SwipeableDrawer I've provi ...

Is there a way to eliminate the white border surrounding this input field? (JSFiddle link included)

http://jsfiddle.net/gn3LL/ .error { background-color: red; } <input id="firstname" class="custom error" name="first_name" type="text" placeholder="" class="input-xlarge"> I am trying to remove the small white border around the inside of the inpu ...

Encountered an error while attempting to load next.config.js

Having cloned the repository, I proceeded to create and set up my .env.local file. After running npm i, I then executed npm run dev. The server initiated successfully, with the environment being loaded from .env.local. However, it abruptly failed, displayi ...

Eliminate border around image

I've been trying to get rid of the image border using different methods img { border: 0px; } I even attempted to remove it from the browser console with this code border: none !important This is what my html code looks like <div id="startD ...

"Utilizing ReactJS and Typescript: A guide on initiating a Redux dispatch event through an axios

Looking for help with ReactJS typescript and redux dispatch events when calling APIs using axios interceptors? Check out my code snippet below. Codesandbax Repo App.tsx import "./App.css"; import "bootstrap/dist/css/bootstrap.min.css" ...

Center align text in the uib-progressbar

Is it possible to center align text in the uib-progressbar? I attempted using position:absolute, but I would like to display a list of progress bars in a UI grid that includes scrollable content. The goal is for the text to remain fixed while the progress ...

I completed the footer on my website, but as I zoom in on the page, everything becomes jumbled and overlapped

Hey there, I'm currently dipping my toes into the world of HTML and CSS with hopes of creating a visually appealing website. Everything was going smoothly until I reached the footer section. At first glance, it looked perfect but upon zooming in, all ...

Text box size in user input not adapting on mobile devices

Website: Visit the Cutter Travel Calculator here I've encountered an issue with my user input text boxes on mobile. Despite setting their width using the formidable forms plugin, the size adjustment doesn't seem to apply when viewed on mobile de ...

Content hidden by spoiler buttons may overlap with other spoiler buttons

I've created some spoilers that reveal information when clicked on. When I clicked on spoiler1, the content slid underneath the other spoilers strangely. Here's an example of what happened: http://gyazo.com/4571423534e2442dc960d119c668dfa8 Why ...

Is it possible to utilize relative paths with webpack dev server in React JS projects?

While running the development server on localhost:3000 using npm run start, everything functions as expected. I am utilizing react-scripts and have not ejected the react app. Currently, my goal is to configure the dev server behind a reverse proxy so that ...

Exploring the possibilities of integrating the cutting-edge Next.js Image component with the sleek Material

Material UI includes components that have image parameters, like the following: <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" /> In the latest version of Next.js (v10), there is a newly introduced Image component tha ...

Enhance your web design skills by customizing Bootstrap5 framework styles using the @layer feature

Here is the HTML code I am working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name=& ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...

I've noticed a plethora of unused JavaScript/CSS in a website's ReactJS code. However, I'm unsure of how to reverse map it back to the source code files in order to make the necessary changes

My website currently has a loading time of 10 seconds, and we are looking to reduce it to around 3 seconds. I have a couple of questions regarding this: 1. When analyzing the bundle loading in the network tab of developer tools, I notice some JS/CSS files ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

Why are two vertical scrolls appearing on the screen simultaneously?

I utilized this method to hide the body scrollbar initially and then display it upon clicking a link: $('body').css('overflow', 'hidden'); $('#site').click(function(e) { $('#wrapper').remove(); $(& ...

An issue with Docker arose when attempting to route to: localhost on port 5000

An issue arises while working with an express-react app on docker. https://i.stack.imgur.com/PrhkH.png https://i.stack.imgur.com/lB5Jp.png I consulted this React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (E ...

Having trouble with webpack displaying CSS background images?

I've set up the html boilerplate using webpack. I'm currently encountering an issue where calling an image in my scss file like "background: url('/img/img.png');" isn't working. I've included the webpack file and folder struct ...