SGhaleb
SGhaleb

Reputation: 1007

Set value from string to number

I am using React-native and the <Picker /> component.

The problem I am having, is that the value='1' is a string, but I would like it to return a number. I have seen ways to parse it, but I am unsure how to do this in react-native.

class TestPage extends Component {
  constructor(props){
    super(props);
    this.state = {
      myNumber:0
    }   
  }

  componentDidMount(){
  }

  render(){
    console.log('My value : ',this.state.myNumber);
    return (
      <View>
        <Picker
          selectedValue={this.state.myNumber}
          style={{ height: 50, width: 150 }}
          onValueChange={(itemValue) => this.setState({myNumber: itemValue})}>
          <Picker.Item label="One" value="1" />//The value here 
          <Picker.Item label="Two" value="2" />
        </Picker>
      </View>
    );
  }
}

Thank you.

Upvotes: 2

Views: 2686

Answers (3)

pryahin.v
pryahin.v

Reputation: 365

For me, the better way - use unary "+":

this.setState({myNumber: +itemValue})

Upvotes: 2

GibboK
GibboK

Reputation: 73908

Try to use the following:

onValueChange={(itemValue) => this.setState((itemValue)=>{myNumber: Number(itemValue)})}>

Upvotes: 0

Tholle
Tholle

Reputation: 112777

You can parse the string to a number with the parseInt function or the Number constructor.

this.setState({myNumber: parseInt(itemValue, 10)})

Upvotes: 1

Related Questions