Search code examples
javascriptreactjsreact-nativestylesheet

React Native, how to remove old style and add new


I want remove old style (Hidden) on View and set new style (InputContainer) when onPress is called.

This source adds new style, but how do I remove old style?

showNext = (id) => {
  this.refs["block-" + id].setNativeProps({
    style: styles.Hidden
  });
  id++;
  this.refs["block-" + id].setNativeProps({
    style: styles.InputContainer
  });
}

render() {
  return (
    <KeyboardAvoidingView style={[styles.Container]}>

      <View style={styles.InputContainer} id="block-1" ref="block-1">       
        <Text>Block 1</Text>
        <DefaultButton onPress={() => this.showNext(1)}>Ok</DefaultButton>
      </View>

      <View style={styles.Hidden} id="block-2" ref="block-2">       
        <Text>Block 2</Text>
      </View>

    </KeyboardAvoidingView>
  )
}

styles

const styles = StyleSheet.create({
  Container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  Hidden: {
    display: "none"
  },
  InputContainer: {
    width: "80%"
  }
});

Solution

  • I think you could do something simpler

    state = {
      pressed: false
    }
    
    
    showNext = () => {
      this.setState({pressed: !this.state.pressed})
    }
    
    render() {
      return (
        <KeyboardAvoidingView style={[styles.Container]}>
    
          <View style={this.state.pressed ? styles.InputContainer : styles.Hidden} id="block-1" ref="block-1">       
            <Text>Block 1</Text>
            <DefaultButton onPress={showNext}>Ok</DefaultButton>
          </View>
    
          <View style={styles.Hidden} id="block-2" ref="block-2">       
            <Text>Block 2</Text>
          </View>
    
        </KeyboardAvoidingView>
      )
    }
    

    it should also work dynamically:

    showNext = (id) => {
      this.setState({[`blockPressed-${id}`]: !this.state[`blockPressed-${id}`]})
    }
    

    and

     <View style={this.state.blockPressed-1 ? stlyes.InputContainer : styles.Hidden}>       
        <Text>Block 1</Text>
        <DefaultButton onPress={() => showNext(1)}>Ok</DefaultButton>
      </View>