noa-dev noa-dev - 4 months ago 8x
Javascript Question

ES6 react state change doesn't affect render inline if clause

i have this subcomponent which renders a "report bugg" button and should display the report bugg form when it is being pressed.
e.g : button pressed -> state update to report_toggle = true

As seen in this code:

import React from 'react';
import ReportBox from './ReportBox';

class ReportBugButton extends React.Component {

this.toggleReportBox = this.toggleReportBox.bind(this);
this.reportSubmit = this.reportSubmit.bind(this);

this.state = {
report_toggle: true
this.state.report_toggle ? this.state.report_toggle = false : this.state.report_toggle = true;
console.log("State ist: ", this.state.report_toggle);

render() {
<a href="#" onClick={this.toggleReportBox} className="report-button tooltip" title="Report a bug"><i className="fa fa-bug"></i></a>
{ this.state.report_toggle ? <ReportBox toggleReport={this.toggleReportBox} submitReport={this.reportSubmit} /> : '' }

export default ReportBugButton;

When the Report Button is clicked the console log perfectly shows that the state is being updated since it always changes between "State is: true" and "State is: false".

Unfortunately the inline if in the render method doesn't seem to care much since it doesn't display the component if it the state is true.

If I set the state true by default it is being displayed , but not being hidden when its set to false by clicking.

Any ideas ? ... :)


You are changing state the wrong way. You should NEVER modify the state variable directly.

Use this.setState.


   this.setState({ report_toggle: !this.state.report_toggle });

Only when you call this function, is the render function triggered and re-rendering is done (only if some state variables changed).