Search code examples
javascriptreactjsreduxtextareastyled-components

Using Textarea inside of styled components makes it write backwards by resetting position of cursor in ReactJS


I am using Textarea from react-textarea-autosize and styled from styled components. I am writing a renderForm function inside a class which renders a form including a StyledTextarea. After analyzing, I have found out that using the Styled, each time I write a character, the positon of the cursor resets in the beginning so it makes it write backwards. I have checked using just a simple <input>, just a simple <Textarea> and all of them works normally. Just when I add the styled component, it behaves like this. The code snippet is given below:

class ActionButton extends Component {
    renderForm() {
        const StyledTextarea = 
            styled(Textarea)`
            resize: none;
            width: 100%;
            overflow: hidden;
            outline: none;
            border: none;
          `; 

        return (
            <StyledTextarea
            autoFocus
            onBlur={this.closeForm}
            value={this.state.text}
            onChange={this.handleInputChange}
          />
        );
    }

    render() {
        return renderForm();
    }
}

This is my first post in stackoverflow. Please pardon any mistakes.


Solution

  • I found out that the declaration of StyledTextarea is causing the problem. If it is declared outside the class, it works fine. I am not sure why though. So the code snippet should look like:

    const StyledTextarea = 
        styled(Textarea)`
        resize: none;
        width: 100%;
        overflow: hidden;
        outline: none;
        border: none;
      `; 
    
    class ActionButton extends Component {
        renderForm() {
            return (
                <StyledTextarea
                autoFocus
                onBlur={this.closeForm}
                value={this.state.text}
                onChange={this.handleInputChange}
              />
            );
        }
    
        render() {
            return renderForm();
        }
    }
    

    Of course, if there are dependencies from inside the class/states/props, then you have to make a function and pass the dependencies as parameters.