textarea not populating with default value but showing value on top of text area instead?

Viewed 2371

I have this code here and when it renders it doesn't show the this.props.child within the textarea but it shows on top of the textarea,

renderNormal(){
    return (<div className="commentContainer">
        <div className="commentText">{this.props.child}</div>
        <button onClick={()=>{this.edit()}} className="button-primary">EDIT </button>
        <button onClick={()=>{this.delete()}} className="button-danger">DELETE </button>
    </div>);
}  

renderForm(){
    return (<div className="commentContainer">
        <textarea defaultValue= {this.props.child}> </textarea>
        <button onClick={()=>{this.save()}} className="button-primary">SAVE </button>
    </div>);
}

render(){
    if(this.state.editing){
        return this.renderForm();
    }else {
        return this.renderNormal();
    }

}

I'm passing in the child value like this,

ReactDOM.render(<div className="board"> CHILD1<Movie/> CHILD2<Movie/> </div>, document.getElementById('root'));

I'm not sure if the above is the right way to do this but when i try to do it this way

ReactDOM.render(<div className="board"> <Movie>CHILD1</Movie> <Movie>CHILD2</Movie> </div>, document.getElementById('root'));

I get an error.

I'm very new to react, please be patient I'll try my best to understand. THanks for helping.

1 Answers

In order to display children, you need to use the children property (which is special), not the child property (which is not). So:

<div className="commentText">{this.props.children}</div>

and

<textarea defaultValue= {this.props.children}> </textarea>

But children can be a string OR another node/element tree, which will work properly for renderNormal() but not for renderForm() if you include anything other than a string inside the textarea.

An example of something that would fail in in the renderForm() branch:

<Movie><span>Span element can't be a defaultValue</span></Movie>

I think you want a property instead:

<div className="commentText">{this.props.value}</div>

and

<textarea defaultValue= {this.props.value}> </textarea>

Then, when you render it (fixing some syntax errors from your original post):

ReactDOM.render(<div className="board">
    <Movie value="CHILD1" />
    <Movie value="CHILD2" />
  </div>,
  document.getElementById('root')
);
Related