Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - multiline textarea

I'm trying to create multi-line text input field with ReactJS. I've created this component:

var TextInput = React.createClass({
  getInitialState: function(){
    return {currentValue: this.props.children}
  },

  handleChange: function(event){
  //handler
  },

  render: function(){
    return (
        <textarea name="body"
                  onChange={this.handleChange}
                  value={this.state.currentValue}/>
    )
  }
});

I'm rendering it this way:

# jinja2 template
React.render(
  <TextInput>{{ post.body }}</TextInput>,                  
  document.getElementById('post-editing')
);

The problem: If {{ post.body }} is something like #Title \n text, the textarea show it in one line. I am seeing #Title text in my textarea without line breaks. What is the right way to set <textarea> value with ReactJS?

like image 372
Ilya Boltnev Avatar asked Jan 09 '15 15:01

Ilya Boltnev


People also ask

How do you send a multi-line comment entry in react?

Multi-Line Comment If you want to comment something in JSX you need to use JavaScript comments inside of Curly braces like {/*comment here*/}. It is a regular /* Block Comments */ , but need to be wrapped in curly braces.

How do I create a text box in react JS?

You can create a TextBox with icon as a group by creating the parent div element with the class e-input-group and add the icon element as span with the class e-input-group-icon . For detailed information, refer to the Groups section.

Which choice will place a multiline text input field on the page?

To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows.


1 Answers

You are setting the value of the <textarea> the correct way, via the value attribute, the issue is that the string you are getting as the value of this.props.children is actually not what you think it is.

With an input value of "#Title \n text" in your <TextInput> component, the value of this.props.children is actually "#Title \\n text" (notice the double backslash), you need to do something like the following to correctly output the newline character:

    render: function(){
      var value = this.state.currentValue.replace('\\n', '\n');
      return (
        <textarea name="body"
          onChange={this.handleChange}
          value={value}/>
      )
    }
like image 123
Dominic Santos Avatar answered Oct 03 '22 00:10

Dominic Santos