Reputation: 1588
I have this one component which renders another component , please note the else if in the render
constructor(props) {
super(props);
this.state = {
fieldId: "",
rating: -1,
description: "",
showModal: false
};
console.log(props) //week number, beginning with 0
this.showModal = this.showModal.bind(this);
}
.
.
.
showModal() {
this.setState({
showModal: true
})
console.log("clicked show modal")
}
.
.
.
.
.
render() {
var weekId = this.props.weekId;
if (weekId < this.props.livedWeeks) {
return <div id={weekId} className="cube-lived"></div>
} else if (weekId == this.props.currentWeek) { //whenever i click the component right below (cube - green), i want to render, <CalendarFieldModal />
return <div id={weekId} title={weekId} className="cube green" onClick={this.showModal}>
{ this.state.showModal ? <CalendarFieldModal /> : null}
</div>
} else {
return <div id={weekId} title={weekId} className="cube white" onClick={this.showModal}> </div>
}
}
This is the component to that the else if element is supposed to render on click
import React from 'react'
import './CalendarFieldModal.css'
class CalendarFieldModal extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
<section className="modal-main">
<p>hi</p>
</section>
</div>
)
}
}
export default CalendarFieldModal;
this is its css
p{
font-size: 10000px;
color: blue;
}
But whenever I click i cant see anything appearing, so im wondering whats the issue, why is it not rendering anything? As for example the simple
that I want to render as a test to see if it works.
EDIT:
I figured that whenever I click the component for the first time, the showModal state is logged in the console as false, and it wont show up as true until the second click. But anyway it still wont render the other element even with double click, so still stuck there
Upvotes: 1
Views: 91
Reputation: 656
Your code is actually working, it's just because your css font size in CalendarFieldModal is too large to render in a proper position, and the reason that every time you click the component, the showModal State is still false, is because setState
is asynchronous, so console.log
below setState
may execute before the state is actually updated, so if you want to log the state in the console after it's actually updated, instead you can use
this.setState({
showModal: true
}, () => console.log(this.state.showModal))
you can see the difference between after state updating and before state updating in the console.
Upvotes: 2