-
-
Save yunusemredilber/c0598e168ef643fa8e9876b78c447b91 to your computer and use it in GitHub Desktop.
| <!-- Some form --> | |
| <div data-controller="auto-grow-textarea"> | |
| <%= form.text_area :body, cols: 20, row: 2, placeholder: 'Bir yorum yazın...', class:'form-control', data: { action: 'input->auto-grow-textarea#resize', target: 'auto-grow-textarea.input' } %> | |
| </div> | |
| <!-- Some form continued --> |
| import {Controller} from "stimulus"; | |
| export default class extends Controller { | |
| static targets = ["input"]; | |
| connect() { | |
| console.log('auto-grow-textarea controller connected...'); | |
| this.inputTarget.style.resize = 'none'; | |
| this.inputTarget.style.minHeight = `${this.inputTarget.scrollHeight}px`; | |
| } | |
| resize(event){ | |
| event.target.style.height = '5px'; | |
| event.target.style.height = `${event.target.scrollHeight}px`; | |
| } | |
| } |
Well, I made it in the CSS but it's a nice tip! It might help others. Thanks, @goulvench.
Just a note:
I was trying to implement this solution and it worked perfectly until I tried to submit a form with validation errors. Then the auto-growth broke and I got Error: Missing target element "auto-grow-textarea.input".
I'm using Rails 7 with Turbo and forms are submitted via AJAX so I figured the lack of actual reloading was somehow messing with the process. I'm not sure exactly what information gets persisted/reloaded during these requests, but I figured the textarea had to be part of it, so I moved the controller declaration from the parent element to the <textarea> element itself. It worked. In the end, it looked like data: { controller: "auto-grow-textarea", action: ...
Just sharing in case others end up here with the same issue.
Small improvement: you can add
this.inputTarget.style.overflow = 'hidden';at the end of theconnectmethod to prevent the scrollbar from appearing when adding text.