Naomi Naomi - 2 months ago 11
Javascript Question

Place content outside DIV in react when toggle

I am creating a toggle in React and it is working when I am pressing the button. What I want to do is to place the courseBody outside of the div with

className="showcourses-field"
because I want the courses to be displayed under the button. When I put
{coursebody}
inside the div it works but it doesn't work when I place it outside the div. How can I place it outside the div?

JS

class ShowCourses extends React.Component {
constructor(){
super();
this.state= {
showingcourses: false

}
}

render(){
let courseBody;
let buttonText ="Show More Courses";
if (!this.state.showingcourses) {
courseBody = this.props.body;

} else {
courseBody = <Course coursename="Food" status="Progress" progress="43%" />
buttonText = "Hide courses";

}


return(
<div className="showcourses-field">
<button className="showbutton" onClick={this._toggleCourse.bind(this)}>{buttonText}</button>

{courseBody}
</div>




);


}
_toggleCourse(event){
event.preventDefault();
this.setState({
showingcourses: !this.state.showingcourses
});
}
}

Answer

outside of className="showcourses-field" Div? you know you have to have only one element in return, so just create another Div :

<div>
  <div className="showcourses-field">
    <button className="showbutton" onClick={this._toggleCourse.bind(this)}>{buttonText}</button>    
  </div>
  {courseBody}
</div>