monsterpiece
monsterpiece

Reputation: 779

conditional render not changing after state change

I'm new to React and i'm trying to perform a conditional render within a stateless child component. When I update my state to force the condition to change, nothing happens.

I've checked to make sure that my callback function is actually changing the state which it is. I've made sure that props is working correctly as I am able to retrieve other data via props from the child.

//main app component

this.state={
FileViewable: false
}

 changeViewStatetoTrue = () =>{
   this.setState({FileViewable:!this.state.FileViewable}, function (){
     console.log(this.state.FileViewable)
   });

//there are more routes but I just wanted to include the route in question
  <Switch>
        <Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.FileViewable}/>}/>
      </Switch>

//Body component where the conditional rendering should happen, there is a Tesseract OCR API call being made here, i've left it out because it works fine

  render(props) {

      var documentView;

      if(!this.props.fileviewableState){

      documentView =   <div> view number 1 </div>

      } else  {
      documentView =  <div>

          <h1>view number 2 </h1>

             </div>
      }

I don't see any error messages and the console logs that the state is being changed. I don't know why this is happening?

Upvotes: 1

Views: 1149

Answers (2)

Dov Rine
Dov Rine

Reputation: 840

try changing:

if(!this.props.fileviewableState)

to:

if(!this.state. FileViewable)

Upvotes: 0

Will Jenkins
Will Jenkins

Reputation: 9787

Possible bug is here:

  <Switch>
      <Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.FileViewable}/>}/>
  </Switch>

Should be:

<Switch>
    <Route path="/app" render={props=><Body {...props} changeViewStatetoTrue={this.changeViewStatetoTrue} fileviewableState={this.state.FileViewable}/>}/>
</Switch>

(fileviewableState={this.FileViewable} should be fileviewableState={this.state.FileViewable}

Upvotes: 1

Related Questions