Xavier C.
Xavier C.

Reputation: 1817

split() method on state value in React Native

I've got town value (in an object) like:

75000 - Paris Ile-de-France

I'm trying to get the second part of my town state value using the split method:

<Text>{this.state.town.split("-")[1].trim() || ''}</Text>

But it seems split method is taken as an element of the object. I've got this error:

Cannot read property 'split' of undefined.

Any idea?

UPDATE :

Ok, it's undefined at start point, before I update the state of town.

Now I try to put a condition before it tries to split my string, but I fail. I'm doing this, but it returns an unexpected token:

<Text style={styles.selectedTown}>{
      return (this.state.town !== {}) ? this.state.town.split('-')[0].trim() : '';
    }</Text>

Upvotes: 2

Views: 24562

Answers (1)

Cobus Kruger
Cobus Kruger

Reputation: 8615

There is a difference between undefined and defined as an empty object. Try this:

<Text style={styles.selectedTown}>{
      (this.state.town !== undefined) ? this.state.town.split('-')[0].trim() : ''
    }</Text>

Upvotes: 2

Related Questions