0

This is an ideal methodology question. I am new to react-native and I am developing an app in which I am asking people to enter the list of cars they own.

When they arrive at the app screen, they see the fields to enter one car's information.

But when they press the 'Add car' button below the above input fields, on the same page, they should be able to see one more set of fields to add information about another car.

What is the ideal way to do this,

I have done following,

  • I have one set of car information fields displayed by default in render function
  • After that, I have an 'add car' touchable highlight
  • When the touchable highlight is clicked, a function is called that returns , new set of fields to be added (Textinput>, etc. )

How do I add the information returned on the page? Should I update a state variable that will be "" at the start and will contain "Textinput etc." later?

Parth Tiwari
  • 855
  • 2
  • 9
  • 23
  • 2
    are you going to hide add car text field in initial rendering and after button press , do you want to show input textfield?? – Chiranjhivi Ghimire Jun 02 '16 at 04:13
  • The previous car textfield will stay. I think this is a similar question,http://stackoverflow.com/questions/35524026/react-native-dynamically-add-element-to-dom-on-button-press?rq=1 – Parth Tiwari Jun 02 '16 at 04:29
  • 2
    yes you can rerender your component by changing in state, first set any variable as false in state and when you press make that variable true in state by this.setstate({}); then, use inline if else state for proper rendering your next car textinput field. :) – Chiranjhivi Ghimire Jun 02 '16 at 04:49
  • @SusylGhimire , excellent advice, it worked using the boolean state variable – Parth Tiwari Jun 02 '16 at 05:46
  • 1
    haha you should vote me up than :) #cheers – Chiranjhivi Ghimire Jun 02 '16 at 06:16

1 Answers1

1

This sounds like an ideal use case for map:

updateCar (index, name) {
  let cars = this.state.cars

  // Update the value
  cars[index].name = name

  this.setState({
    cars: cars
  })
}

addCar () {
  let cars = this.state.cars

  // Add the new car
  cars.push({ name: '' })

  this.setState({
    cars: cars
  })
}

render () {
  let me = this

  return (
    <View>
      {this.state.cars.map(function(car, index) {
        return (<TextInput onChangeText={(text) => me.updateCar(index, name)}
                          value={me.state.cars[index].name} />)
      })}
      <TouchableHighlight onPress={this.addCar}>
        <Text>Add Car</Text>
      </TouchableHighlight>
    </View>
  )
}

Remember to use this.addCar.bind(this) in your constructor() for each method there.

The map() function allows us to iterate over a collection and return a value for each item in that collection. Here we can take the raw car data, and return UI elements.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74