2

I want to do some conditional rendering based on what is in state. My state looks something along the lines of this:

state = {
  text: '',
  properties: {
     someMoreData: [{...}]
  },
  moreData: ''
}

I want to do conditional rendering based on whether or not the someMoreData field exists within the properties key in my state. My current code looks like this:

render () {
     console.log(this.state)
     if('someMoreData' in this.state.properties)
     return (
         <div>
          ..
         </div>
     )
}

React is throwing an error stating Cannot use 'in' operator to search for 'someMoreData' in undefined

How to can i format my code so that if the someMoreData field exists, I get my JSX, and if not i render some other JSX.

1
  • 1
    That's not really how the in operator works nor how it is used in JavaScript. If you simply need to know whether or not someMoreData is not falsy, you can do if (this.state.properties.someMoreData) { ... some code ... }. Commented Oct 4, 2019 at 22:17

2 Answers 2

2

Typically, you just do something like:

render() {
  return (
    <div>
      {
        this.state.properties.someMoreData && (
          <div>Some other JSX stuff</div>
        )
      }
    </div>
  )
}

However, Cannot use 'in' operator to search for 'someMoreData' in undefined seems to indicate that for whatever reason this.state.properties is undefined. Not sure why with only the code you've posted, but I would look at that.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do that using ternary operators

render() {
  return (
    <div>
      {this.state.properties.someMoreData ? 
          // someMoreData exists
          (<div>Some JSX stuff</div>) 
          :
          //someMoreData does not exist
          (<div>Some other JSX stuff</div>)
      }
    </div>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.