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?
Best Solution
You are setting the value of the
<textarea>
the correct way, via thevalue
attribute, the issue is that the string you are getting as the value ofthis.props.children
is actually not what you think it is.With an input value of
"#Title \n text"
in your<TextInput>
component, the value ofthis.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: