Enhancing the input field in React with a custom wrapper and dynamic height adjustment

I'm attempting to create an input component that wraps the text and increases in height with each new line, similar to how it works on desktop Facebook. When you select someone, open the message box, and start typing, the input grows larger with each additional line of text.

Currently, I am using a textarea for this purpose: <Input />

const Input = styled.textarea`
  border: 0;
  outline: none;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 14px;
  width: 100%;
  overflow-wrap: break-word;
  height: 24px;
`;

Once I have entered 5 lines of text, I want a scroll bar to appear. How can I achieve this?

Answer №1

If you don't necessarily need a textarea, you can achieve the desired functionality using the contenteditable attribute. Simply apply it to a <div> element and set a maximum height for the scrollbar to appear:

.demo {
  width: 100px;
  min-height: 20px;
  max-height: 100px;
  overflow-x: hidden;
  overflow-y: scroll;
  border: 1px solid black;
}
<div class="demo" contenteditable></div>

If a textarea is required, then utilizing a script to handle resizing is necessary. There are various effective methods outlined here: CSS Tricks: Auto growing inputs and textareas

edit For illustration purposes, here's an example in React using the contentEditable attribute (camelCase for React JSX) along with a placeholder. The placeholder is incorporated using a pseudo element:

const ContentEditable = ({ placeholder }) => (
  <div class="demo" contentEditable="true" placeholder={placeholder}></div>
);

ReactDOM.render(
  <ContentEditable placeholder="Type something..." />, document.getElementById("react")
);
.demo {
  width: 100px;
  min-height: 20px;
  max-height: 100px;
  overflow-x: hidden;
  overflow-y: scroll;
  border: 1px solid black;
}

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color: #555;
  pointer-events: none;
  display: block;
}
<div id="react"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

What was the purpose of acquiring knowledge in mongoose js?

As I browse through YouTube for tutorials on projects involving Express JS and MongoDB, I noticed that most of them use Mongoose JS. This leads me to question the necessity of learning Mongoose. Why is it important for me to learn Mongoose if I can work ...

Simple inquiry: PHP and HTML formatting essentials

I've reached a point in my coding where there is an abundance of code and a heavy reliance on certain server conditions for HTML outputs. Is there a way to work around this issue, similar to the following PHP snippet: <?php if (cond) echo '& ...

Changing Bootstrap variables within a React application: A step-by-step guide

I've been working with facebook's create-react-app and I successfully added SASS to my project. Now, I'm trying to incorporate Bootstrap and customize the theme but running into some issues. Here's what my setup looks like: package.jso ...

Is the audio playback in React Native unsuccessful because of an error in decoding the audio?

While attempting to play an audio file from a URL using react-native-audio, the audio manager tried to start playing the file before it had finished loading. This resulted in playback failure due to an audio decoding error... I searched for a solution on ...

What is the process of turning a picture from a menu file into a clickable link?

I have created a menu with some images included, and I want them to be clickable links. However, currently only the text on top of the images acts as a link when hovered over. I would like the entire image to be clickable, not just the text. I believe I ...

Create a search bar using HTML and CSS that utilizes the GET method

My current challenge involves creating a search functionality using HTML based on the username entered, such as 'user'. Upon clicking the search bar, the page should redirect to http://localhost/searchuser/user I am encountering difficulties wi ...

Restricting Options in jQuery/ajax选择列表

Although there are similar questions posted, my specific issue is that I am unsure of where to place certain information. My goal is to restrict the number of items fetched from a list within the script provided below. The actual script functions correct ...

Error: Reading the property 'any' of an undefined object resulted in a TypeError after an update operation

After updating multiple npm packages in my application, I encountered a series of errors that I managed to resolve, except for one persistent issue! TypeError: Cannot read property 'any' of undefined at Object.<anonymous> (/home/cpt/Deskto ...

Is Vue the next contender against React Native and Flutter?

I find vue and nuxt very enjoyable to work with. However, I believe that the future lies in mobile development or rather "developing for both mobile and web using the same code." Is there an efficient method to achieve this with vue? Or should I consider ...

The transparency of the image remains slightly see-through even after adjusting the opacity value

Functionality: The current page design includes a translucent background with an opacity of 0.68, and an image placed on top with a full opacity of 1.0. However, the issue arises when the image inherits the transparency property from the background. The g ...

Welcome to the interactive homepage featuring multitouch authentication

I am looking to design a homepage that is interactive based on touch input. For instance, if the user uses 5 fingers to touch the screen, similar to the green circles in the image below, they will be redirected to a specific homepage. If they touch in a di ...

Creating an Angular form that adapts to changing input values

I'm encountering a problem with angular not recognizing the dynamic values from my inputs. My objective is to have angular populate hidden form fields with lat/lon when a user clicks on the map. The user then submits the form, but the data ends up mi ...

Creating a new state by merging the data from two existing states in Next.js

Using the useState hook, I am trying to merge data from two different states (text and inputs) into a third state called alldata. Here is what I have attempted: const [alldata, setAlldata] = useState({}) const [text, setText] = useState({ category: "prod ...

Incorporating Auth0 into the MERN technology stack

I am currently working on integrating Auth0 authentication into my MERN stack project. I find it confusing that React only appears to be connecting with the Auth0 server during authentication, as demonstrated in this tutorial. https://auth0.com/docs/quick ...

CSS technique for adjustable column width in HTML tables

Important Note: The HTML to PDF rendering engine I am using disables JavaScript by default, so I am seeking solutions that utilize CSS only. Within my report, there is a table utilized for accounting purposes featuring 11 columns: The first column serve ...

Utilizing jQuery for easy drag-and-drop functionality in web development

I have two lists which are currently using jQuery for functionality. An example can be found here. I need the same basic functionality but with some modifications: Instead of just getting all sortable items by clicking "Get items," I want to be able to dr ...

Aligning elements next to each other in html / css without using any top margins

How can I arrange four blocks of text side-by-side, center them over a background image, and ensure they respond well on different screen sizes without using tables? I typically use tables for this layout, but I've heard that CSS/HTML5 can achieve th ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

PHP code to display or conceal tables

I am facing a challenge in my PHP code where I need to hide a table based on a specific condition. Despite trying to use CSS for this purpose, it seems that CSS does not recognize the if condition and always overrides it. I am looking for a solution that ...

Modifying the initial state values in Redux Form is prohibited

I'm facing an issue with my redux-form component. I have successfully passed the initial form state values, but when I try to edit them by clicking inside the form, nothing happens. I've diligently followed all the documentation available, includ ...