Home > Software design >  Wrapping and height increasing input React CSS
Wrapping and height increasing input React CSS

Time:10-14

I try to make an input component where the text is wrapping and height of the input increases at each new line appear. I mean something like on desktop facebook. When you click on someone, open the message box and write something in the input, the input becomes larger every new text line.

I am using textarea for it: <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;
`;

And after entering 5 lines of text, the scroll bar should appear. How can I do this?

CodePudding user response:

If it doesn't have to be a textarea, the contenteditable attribute can do this - add it to a <div> and set a max 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 it must be a textarea, then you will have to use a script to resize it - there's some good approaches listed here: CSS Tricks: Auto growing inputs and textareas

edit Here's a demo in react, using the contentEditable attribute (use camelCase for React jsx) with a placeholder. The placeholder is added 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>

  • Related