Having a fixed bottom line bar that does not affect the length of the div when

I am working on creating an input field with a rounded bottom line. My goal is to make the main div expand or contract based on the length of the input, with specified minimum and maximum lengths.

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

Instead of taking up the entire width, I just want the bottom bar and surrounding div to adjust in size within a range, such as a minimum of 100px and a maximum of 300px

Input code:

import React, { memo, useState } from 'react'
import { CommonInputProps } from '../Input'
import { twMerge } from 'tailwind-merge'

export interface NoStyleProps
  extends Omit<CommonInputProps, 'form' | 'placeholder'> {
  mainDivClass?: string
}

const NoStyle = ({
  register,
  className,
  hasError,
  mainDivClass,
}: NoStyleProps) => {
  const [isFocused, setIsFocused] = useState(false)

  const handleFocus = () => {
    setIsFocused(true)
  }

  const handleBlur = () => {
    setIsFocused(false)
  }

  return (
    <div className={twMerge('relative w-auto', mainDivClass)}>
      <input
        type="text"
        className={twMerge(
          `outline-none bg-white text-center `,
          className,
        )}
        autoComplete="off"
        {...register}
        onFocus={handleFocus}
        onBlur={handleBlur}
      />
      {hasError && (
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-error rounded-full"></div>
      )}
      {isFocused && !hasError && (
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-primary rounded-full"></div>
      )}
    </div>
  )
}

export default memo(NoStyle)

Answer №1

If you're in search of a solution,

This code snippet adjusts the input field's width and border based on the length of the value.

Here is the Javascript (Reactjs) code:

const [inputValue, setInputValue] = useState('');
const [inputWidth, setInputWidth] = useState('auto');

const handleChange = (event) => {
    setInputValue(event.target.value);
    setInputWidth(`${event.target.scrollWidth}px`);
}

useEffect(() => {
    if (inputValue === '') {
        setInputWidth('10px')
    }
}, [inputValue])

And here is the JSX implementation:

<div className="flex justify-start items-start w-screen h-screen p-10">
  <input
    type="text"
    value={inputValue}
    style={{ width: inputWidth }}
    onChange={handleChange}
    className="leading-none bg-gray-200 no-outline"
  />

  <div
    className="absolute flex justify-center items-center mt-6 h-1 bg-[red] rounded-full"
    style={{ width: inputWidth }}
  ></div>
</div>;

Kindly take note: This code utilizes Tailwind CSS for styling. If the styles do not display properly, consider converting it to regular CSS or incorporating the TailwindCSS library.

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

When using the <object> tag, it may not always render at 100% height as intended

Application Inquiry I am seeking assistance with a web page that features a title, and a sticky menu bar at the top, allowing the rest of the space for displaying content. When a menu item is clicked, the objective is to load a page in the content at full ...

problem with maximum width in Internet Explorer 8

Struggling with a compatibility issue in IE8. Here's my HTML code - Test in any browser and then try in IE8 jsfiddle.net/G2C33/ The desired output should be like this The problem is that the max-width property doesn't work in IE8. Note: Test ...

Best practices for evenly distributing images within a navigation bar?

Within a horizontal navbar, I have various small images that are currently spaced out with different intervals between them. Each image has its own unique spacing from the others. I am looking to achieve consistent spacing between each image in this horiz ...

What is the best way to obtain the final HTML output once all scripts have been executed

Is there a way to obtain the final HTML after all scripts have been executed? The scripts on the page are adding and changing controls and CSS, and I want to see the HTML of the display as a static page. Is there a method to achieve this? Edit: For exa ...

Immediate add/modify

Exploring various websites online, I've come across platforms that offer the ability to manipulate data effortlessly. From inserting records to deleting and editing them, the process seems seamless. What's intriguing is how, upon clicking the r ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

How to automatically reset a form after submission in React using Ant Design?

When using the antd template for form design, I encountered an issue where form input values were not getting cleared after submission. I attempted to use this.props.form.resetFields(), but it resulted in the following error: Unhandled Rejection (TypeErro ...

Using icons and additional information in the dataset with Materials UI Datatable without sacrificing sorting functionality

I am looking to enhance my Materials UI Datatables with icons indicating cost changes. These icons should be colored red or green, and accompanied by a keyword explaining the change. +-------------------+ | Cost | +-------------------+ | ...

I'm looking to center my btn button vertically and horizontally over two images using Bootstrap 5 in a responsive manner. How can I achieve this?

Any tips on how to position my btn button both vertically and horizontally in the center on top of two images? I want it to look like this: https://i.sstatic.net/Rezrd.png This is the code for my button: <a class="btn btn-primary" href=" ...

Diverse Browser Outcomes with jQuery CSS

Currently, I am in the process of developing an app that utilizes percentages as offset positions for ease of calculation. For a visual example, you can visit this link: http://jsfiddle.net/WeC9q/1/embedded/result/ Although the zooming feature functions ...

Display concealed information upon clicking

Is there a way to reveal hidden content only after clicking on the "View" link instead of hovering over it? I have tried implementing it so that the content appears on click, but it doesn't seem to be working as expected. How can I achieve this usin ...

User agreement required for HTML5 geolocation custom notifications

Currently implementing HTML5 geolocation on my mobile website. I am exploring the possibility of displaying a custom notification instead of the default web browser notification to request user consent for sharing their location. This custom notification ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

"Using the d-flex class with Bootstrap 4 tables does not allow them to expand to

Since the latest version of Bootstrap 4, it has become more challenging to apply classes like col-md-2 directly to the tr or td elements of a table. A possible solution is to use class="d-flex" in the parent element: <tr class="d-flex"> However, w ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Is there a way to customize the progress bar percentage in Ant design?

I am currently utilizing React JS and importing the Ant Design progress component (refer to https://ant.design/components/progress/). However, I am facing difficulties in dynamically editing the percentage of the progress bar using JavaScript after it has ...

Six Material-UI TextFields sharing a single label

Is there a way to create 6 MUI TextField components for entering 6 numbers separated by dots, all enclosed within one common label 'Code Number' inside a single FormControl? The issue here is that the label currently appears only in the first tex ...

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...