Ycon Ycon - 5 months ago 40
React JSX Question

Conditional getInitialState- if value null

I am having some trouble with getInitialState in react. I have some data that arrives in my props, but it will not always have the key "text".

I want it to just give it an empty value if it doesn't find the props field "text"

I basically want to say
`this.props.photo.info[0].text OR if that doesn't exist, show ''

I tried this with

The below gives an invalid props error:

getInitialState() {
return {
value: ((this.props.photo && this.props.photo.info && this.props.photo.info[0].text) || '')

This gave the same error:

value:this.props.photo.info[0].text || 'empty'

If I do the below, all that gets returned is
[Object, Object]
which makes me think it is returning the value from the first this.props.photo or .info (ie not all the way to info[0].text)

(this.props.photo || this.props.photo.info || this.props.photo.info[0])

This is a sample of my json data in the props

"title": "Item 1",
"info": [
"text": "<h1> I'm a real value </h1> <br/> <p> Not always here</p>",
"title": "Item 2",
"info": [],


I can see why your second example would be [Object Object] but the first one looks like it should work to me, but you will get an error if there is no info[0]. Try the following? -

getInitialState() {
  return {
    value: ((this.props.photo && this.props.photo.info && this.props.photo.info[0] && this.props.photo.info[0].text) || '')