0

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?

2

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

The contenteditable method is fine, but how can I add this attribute to react component? I saw a lib for it react-contenteditable but this component doesn't has placeholder attribute.
sorry I should have included a react example - updated my answer with a react demo that has a placeholder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.