Naomi Naomi - 2 months ago 12
React JSX Question

Element not being displayed when div is removed in react

I am quite new to react but I am trying to pass element from the Course component to my Coursebox component. I am doing this successfully but the button is being displayed since I am not passing that with this.prompt. I would like to remove the div id="course" from the HTML because I only want the course component to be displayed within the couresebox component.

This is my JSX code

class Course extends React.Component {
render() {
return (
<div className="course">

<h3>{this.props.coursename}</h3>
<h4> {this.props.status} {this.props.progress}</h4>
<button>Start exercise</button>


</div>
);
}
}

ReactDOM.render( < Course />, document.getElementById('course'));


class Coursebox extends React.Component {
render() {
return (
<div>
<Course coursename="Negotiation" progress= "20%" status="Progress"/>
<Course coursename="Frontend" progress="56%" status="Progress"/>
<Course coursename="Food" status="Progress" progress="43%"/>

</div>

);
}
}

ReactDOM.render( < Coursebox />, document.getElementById('coursebox'));


and HTML

<header id="header">
</header>
<h3 id="search"></h3>
<div id="coursebox"></div>
<div id="course"></div>


When I remove the nothing is being displayed on the page apart from the header. Since I am passing the element from Course to the Coursebox component, shouldn't I be able to remove the course div from the HTML?

If it is still needed, why is that?

Is there a way for me to only display the button when a course name is being passed?

Thanks :)

Answer

1.) See this line

 ReactDOM.render( < Course />, document.getElementById('course'));

You are explicitly asking react to render Course in a div which has id 'course'.

If you remove this, it will not render separately, but only from within Coursebox element. Then you can safely remove that div.

2.) Yes, you can only show button when course name is passed. Using If condition ternary operator. Add your button in following way:

<h3>{this.props.coursename}</h3>
<h4> {this.props.status} {this.props.progress}</h4>
{ this.props.coursename ? (<button>Start exercise</button>): null}
Comments